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:
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
:
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:
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