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:

JavaScript

Link code :

JavaScript

getInitialProps // _app.tsx

JavaScript

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.

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement