I’m trying to add a link to redirect users to the create page, But when I clicked on the link I got the following error:
TypeError: Cannot read properties of undefined (reading 'cookies')
Link code :
<Link href={link}>Add New Employee</Link>
getInitialProps // _app.tsx
MyApp.getInitialProps = async (context: any) => {
const {req, res, pathname} = context.ctx;
const {language, auth_key} = req.cookies;
return {
lang: language ?? 'ar',
token: auth_key ?? null,
}
};
Advertisement
Answer
You have to write isomorphic code inside MyApp.getInitialProps
because that code can run both on the server (during first page load) or on the client (during client-side navigations).
From getInitialProps
documentation:
For the initial page load,
getInitialProps
will run on the server only.getInitialProps
will then run on the client when navigating to a different route via thenext/link
component or by usingnext/router
. However, ifgetInitialProps
is used in a custom_app.js
, and the page being navigated to implementsgetServerSideProps
, thengetInitialProps
will run on the server.
Here’s a possible implementation to get around your error. It checks if req
is defined before accessing req.cookies
. If it is, then the cookies are retrieved from document
instead.
// Get cookie from `document` on the client-side
const getCookie = (name) => {
const match = document.cookie?.match(new RegExp(`(^| )${name}=([^;]+)`));
return match?.[2];
};
MyApp.getInitialProps = async (context) => {
const { req } = context.ctx;
const language = req ? req.cookies.language : getCookie('language');
const auth_key = req ? req.cookies.auth_key : getCookie('auth_key');
return {
lang: language ?? 'ar',
token: auth_key ?? null,
}
};