Skip to content
Advertisement

Clicking on next/link causing an issue in getInitialProps

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 the next/link component or by using next/router. However, if getInitialProps is used in a custom _app.js, and the page being navigated to implements getServerSideProps, then getInitialProps 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,
    }
};
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement