Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 990
Mammad Mammadli Avatar asked Sep 12 '20 12:09

Mammad Mammadli


People also ask

How do I use Nextjs cookies?

In order to use cookies in Next js, we need to install two packages, cookie, and react-cookie. react-cookie is useful because it allows us to set cookies from the client-side, whereas the cookie package allows us to access cookies from the server-side.

Can I use getServerSideProps in component?

getServerSideProps can only be exported from a page. You can't export it from non-page files. Note that you must export getServerSideProps as a standalone function — it will not work if you add getServerSideProps as a property of the page component.

What is getInitialProps in next JS?

getInitialProps is used to asynchronously fetch some data, which then populates props . Data returned from getInitialProps is serialized when server rendering, similar to what JSON.stringify does. Make sure the returned object from getInitialProps is a plain Object and not using Date , Map or Set .

What is the context in getServerSideProps?

The context parameter is an object containing the following keys: params : If this page uses a dynamic route, params contains the route parameters. If the page name is [id]. js , then params will look like { id: ... } .


Video Answer


1 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: {} }
}
like image 174
james Avatar answered Oct 18 '22 11:10

james