16

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?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Mammad Mammadli
  • 310
  • 1
  • 2
  • 9

7 Answers7

26

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: {} }
}
gazdagergo
  • 6,187
  • 1
  • 31
  • 45
james
  • 5,006
  • 8
  • 39
  • 64
23

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

juliomalves
  • 42,130
  • 20
  • 150
  • 146
  • 1
    Yap, can be accessed using `context.req.cookies.cookieName` too.. – Fahmi Auliya Jun 28 '22 at 10:35
  • @FahmiAuliya Of course, I'm only using the `context.req.cookies['next-i18next']` because `next-i18next` has an hyphen and can't be used as `context.req.cookies.next-i18next`, and that's what OP was trying to access. – juliomalves Jun 28 '22 at 11:11
  • i get exceptionally long loading time on the pages where i implement this any idea ? –  Jul 06 '22 at 09:39
  • 1
    @mangrove108 Sorry, where you implement what exactly? This is simply showing how to get cookies from inside `getServerSideProps` - that in itself would not cause long load times. If you have long page load time due to the logic you have inside `getServerSideProps` then that's another issue. Maybe investigate why that code is taking a long time to run, and create a new question for it. – juliomalves Jul 06 '22 at 11:46
  • mmh @juliomalves i m just checking for context.req.cookies and then if its the case do a redirect nothing special i would say –  Jul 06 '22 at 15:10
  • 1
    @mangrove108 From my experience, that wouldn't cause a significant increase in page load times. Feel free to ask a new question with more details about the issue here on Stack Overflow. – juliomalves Jul 06 '22 at 16:27
  • I made following change ``` - const cookies = qs.decode(context.req?.headers?.cookie ?? ""); // @ts-ignore const cookies = context.req?.cookies;``` – ch4nd4n Aug 08 '23 at 04:38
5

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,
     } 
  }
}
Randall
  • 2,414
  • 3
  • 35
  • 63
4

how are you doing? you can use Something like this :

export async function getServerSideProps(context) {
  console.log(context.req.cookies)
}

so easy and so beautifuly!

1

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 },
  });
MD SHAYON
  • 7,001
  • 45
  • 38
0

inside getServerSideProps function i want to make an authenticated get request to the server. I need to pass in headers {Authorization: Bearer ${storedJwt}, ...} the storedJWT is stored in the browser as a cookie , i tried to access it in the function using const storedJwt = Cookies.get("jwt");

(well i am using this package import Cookies from "js-cookie"; )

i think inside getServerSideProps i cannot access the Jwt stored in the Cookie

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 21 '23 at 13:54
0

You can get the cookies from the context.res.getHeader('Set-Cookie') inside getServerSideProps:

export const getServerSideProps: GetServerSideProps = async (context) => {
    
      const cookieStore: ReturnType<typeof context.res.getHeader> =
        context.res.getHeader('Set-Cookie');
    
      const cookieStoreParsed: { [key: string]: string } = Array.isArray(
        cookieStore
      )
        ? getValuesFromCookie(cookieStore)
        : {};

// to be get value use cookieStoreParsed[SOME_COOKIE_NAME]
      console.log(cookieStoreParsed[SOME_COOKIE_NAME])
    
      return {
        props: {
          ...something you need
        },
      };
    };

Then use the cookie npm package to parse them:

import * as cookie from 'cookie'

const getValuesFromCookie = (cookieStore: string[]) =>
      cookieStore.reduce((acc: { [key: string]: string }, cookieElem: string) => {
        const cookieElemParsed = cookie.parse(cookieElem);
        return {
          ...acc,
          ...cookieElemParsed,
        };
      }, {});