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

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?



Solution 1:[1]

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

Solution 2:[2]

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 {}

Solution 3:[3]

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,
     } 
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gazdagergo
Solution 2
Solution 3