简体   繁体   中英

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 ?

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

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

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!

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']
    
    // ...
    
}

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)

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM