How to get express session in getServerSideProps() – Express, Nextjs

I want to set up a checkout page while preventing users that aren’t connected and do not have any current cart to access this page.

  • I’m trying to implement this verification on getServerSideProps() function.
  • Cart information is stored in express-session‘s req.session.cart.
  • I’m using a custom nextjs server with express.

express-session method

I’m able to verify if the user is connected with a cookie that contains the jwt token for user auth.
To achieve this, when the user login, express put his token in the response data and as a httpOnly cookie.
Then I simply access it like this :

pages/cart/checkout.jsx

...
import * as cookie from 'cookie'
...

export async function getServerSideProps(context) {

  const headerCookies = context.req.headers.cookie
  const parsedCookies = headerCookies ? cookie.parse(context.req.headers.cookie) : null
  const token = parsedCookies?.authToken || null

  let logged = false
  if (token) {
    try {
      logged = verifyAuthToken(token)
    } catch (error) {
      logged = false
      console.log(error)
    }
  }

  if (!logged) {
    return {
      redirect: {
        destination: '/cart',
        permanent: false,
      },
    }
  }

  return {
    props: {}, // Will be passed to the page component as props
  }
}

Now I would like to verify if req.session.cart is empty or not. If it is, I would redirect the user to the cart page.

I believe that express session is only accessible when a request is made to the API. I also believe that only a request from the user concerned is able to get that session.cart info. I thought of making a API call inside getServerSideProps() but since it’s executed server side, it would not be the user’s request and req.session.cart wouldn’t be the same as the user.

How to access express’s session information inside getServerSideProps() ?

cookie-session method

I tried to replace express-session by cookie-session so that my cart info is stored in client’s cookies and then I could fetch them as I did with authToken.
But is it safe to store cart in client’s cookies ? Since the final price asked to the client is taken on cart information. I believe cookies are signed and can’t be altered but I’m not sure.

Anyway, I tried to achieve that without success :

  const headerCookies = context.req.headers.cookie
  const parsedCookies = headerCookies ? cookie.parse(context.req.headers.cookie) : null
  console.log(parsedCookies.session)

Returns something like a jwt token (but isn’t) : eyJjYXJ0Ijp7InVzZXIiOiI2M......9fQ==.
What could I do with this information ? Is it possible to decode it (like jwt does) with my cookie-session secret key and then access info ?