Home > Net >  Unable to use session cookie in server-side request (getServerSideProps) in Next.js
Unable to use session cookie in server-side request (getServerSideProps) in Next.js

Time:12-05

I'm trying to perform a request to a backend service using Axios inside getServerSideProps, but it is failing because the session cookie that is needed for authentication is not included in context.req headers.

The application has its client on a subdomain (e.g. app.domain.com) and the backend service, which is based on Node/Express.js, is on another subdomain (e.g. api.domain.com). The cookie is being sent during authentication and seems to be correctly stored in the browser, but interestingly, it is not stored within the client subdomain, but as part of the backend subdomain (api.domain.com).

I'm using cookie-session for handling the response from Express with the following config flags:

app.use(
    cookieSession({
        signed: false,
        secure: true,
        httpOnly: true,
        sameSite: "strict"
    })
);

I've played with the cookie-session middleware config flags, setting sameSite to "none" and httpOnly to false, with no success. I've also checked the contents of the "context" object in getServerSideProps, just to confirm that the cookie is not being sent to the server.

CodePudding user response:

Assuming you have correctly configured a middleware in your backend to send/accept credentials and accept CORS requests (e.g. https://expressjs.com/en/resources/middleware/cors.html), you can try to add the "domain" flag to cookieSession options.

app.use(
    cookieSession({
        signed: false,
        domain: "your-domain.com",
        secure: true,
        httpOnly: true,
        sameSite: "strict"
    })
);

This way, the cookie will be stored in the "domain scope" and not restricted to your backend subdomain.

  • Related