An Idiosyncratic Blog

🍪 Setting Cookies in Next.js

Published on
·
2 minutes read

When working on a Next.js project, I found this peculiar problem. The client app needed to have an identifier cookie set when a user lands on the page, because certain APIs later in the page depend on this cookie value for some kind of data validation. Which meant setting the cookie on the intial request to the server. My initial thought was to use getInitialProps, but that meant I loose the Automatic Static Optimization feature in Next.js.

Digging through the Next.js documentation, I finally found out it was just a matter of exporting the headers method in next.config.js file.1

module.exports = {
  async headers() {
    return [
      {
        source: '/',
        headers: [
          {
            key: 'Set-Cookie',
            value: `PID: ${generatePID()}`,
          },
          {
            key: 'x-another-custom-header',
            value: 'my other custom header value',
          },
        ],
      },
    ]
  },
}

As seen on L#8, I am setting the cookie using Set-Cookie response header when the user lands on / page. So now I get the advantage of Automatic Static Optimization and can set cookies on request.

Although, when I use /:path* instead of / in the source field, the cookie gets added multiple times when navigating between pages. This happens because every time user navigates to another page, the path value for the cookie changes.

I couldn't find anything in the Next.js docs for overriding options for a Header. 😔 If you have ideas, leave a comment below.

Footnotes

  1. Headers