How to Retrieve Server-Side Cookies in a Next.js App
Accessing cookies while server-side rendering in a Next.js app can present challenges. In this blog, I will share my solution to this problem.
I recently encountered an issue with my Next.js app where it relied on cookies for authentication. However, upon initializing the first page, I discovered that my cookies were not being set.
Here’s an example of the code I had initially, which involved making a GET request to an endpoint using Axios:
1 | Bookings.getInitialProps = async (ctx) => { |
Even though I had Passport.js set up on the server-side endpoint, it failed to authenticate the user on the server-side rendered (SSR) page. The reason was that it couldn’t find any cookies.
To solve this issue, I modified my code as follows, by including the cookies in the headers
:
1 | Bookings.getInitialProps = async (ctx) => { |
The key to accessing cookies on the server-side was to add the following line to the Axios configuration:
1 | headers: ctx.req ? { cookie: ctx.req.headers.cookie } : undefined |
By implementing this change, I successfully made cookies available in the backend of my Next.js app.
Tags: Next.js, server-side rendering, cookies, authentication, Axios, Passport.js