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

10,248

Solution 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

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

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,
     } 
  }
}
Share:
10,248

Related videos on Youtube

Mammad Mammadli
Author by

Mammad Mammadli

Updated on June 04, 2022

Comments

  • Mammad Mammadli
    Mammad Mammadli almost 2 years

    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?