/

How to Retrieve Server-Side Cookies in a Next.js App

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
2
3
4
5
6
7
Bookings.getInitialProps = async (ctx) => {
const response = await axios.get('http://localhost:3000/api/bookings/list');

return {
bookings: response.data
};
};

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
2
3
4
5
6
7
8
9
10
11
Bookings.getInitialProps = async (ctx) => {
const response = await axios({
method: 'get',
url: 'http://localhost:3000/api/bookings/list',
headers: ctx.req ? { cookie: ctx.req.headers.cookie } : undefined
});

return {
bookings: response.data
};
};

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