How to use cookie inside `getServerSideProps` method in Next.js?

Viewed 21014

I have to send current language on endpoint. But getting language from Cookie returns undefined inside getServerSideProps.

export async function getServerSideProps(context) {
    const lang = await Cookie.get('next-i18next')
    const res = await fetch(`endpoint/${lang}`)
    const data = await res.json()

    return {
        props: { data },
    }
}

export default Index;

What is the proper way to get cookie inside getServerSideProps?

5 Answers

You can get the cookies from the req.headers inside getServerSideProps:

export async function getServerSideProps(context) {
  const cookies = context.req.headers.cookie;
  return {
    props: {},
  };
}

You could then use the cookie npm package to parse them:

import * as cookie from 'cookie'

export async function getServerSideProps(context) {
  const parsedCookies = cookie.parse(context.req.headers.cookie);
  return { props: {} }
}

To avoid having to parse the cookies string from context.req.headers.cookie, Next.js also provides the cookies as an object which can be accessed with context.req.cookies.

export async function getServerSideProps(context) {
    const lang = context.req.cookies['next-i18next']
    
    // ...
    
}

From getServerSideProps documentation:

The req in the context passed to getServerSideProps provides built in middleware that parses the incoming request (req). That middleware is:

req.cookies - An object containing the cookies sent by the request. Defaults to {}

You can use parseCookies function with cookie package

import cookie from "cookie"

function parseCookies(req){
    return cookie.parse(req ? req.headers.cookie || "" : document.cookie);
}

And then get access like that.

export async function getServerSideProps({ req} ) {
  const cookies = parseCookies(req);

  // And then get element from cookie by name
  
  return { 
     props: {
        jwt: cookies.jwt,
     } 
  }
}

If you are using Axios this is very simple

  • This will work inside getServerSideProps method. You can't get access to the cookie by using withCredentials because this is on the server.
const { token } = context.req.cookies;
  const response = await axios.get('/staff/single', {
    headers: { Cookie: `token=${token};` },
  });
  • or try (This will work on the client)
  const response = await axios.get('/staff/single', {
    headers: { withCredentials: true },
  });

We can get the cookies from the req.headers inside getServerSideProps without npm

 export async function getServerSideProps(ctx) { 

 const data = ctx.req?.cookies['CookiesName'];
                OR
 const data_1 = ctx.req?.cookies?.CookiesName;

 console.log(data, data_1)

}
Related