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
?
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.
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.
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 .
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: ... } .
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: {} }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With