Get localStorage in NextJs getInitialProps
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
. Docs
This means you will not be able to access localStorage
(client-side-only) all the time and will have to handle it:
Dashboard.getInitialProps = async ({ req }) => {
let token;
if (req) {
// server
return { page: {} };
} else {
// client
const token = localStorage.getItem("auth");
const res = await fetch(`${process.env.API_URL}/pages/about`, {
headers: { Authorization: token },
});
const data = await res.json();
return { page: data };
}
};
If you want to get the user's token for the initial page load, you have to store the token in cookies
instead of localStorage
which @alejandro also mentioned in the comment.
Sonjoy Datta
I am expertise in TypeScript, ReactJs, Redux, Next.js, styled-components, CSS3, SASS/SCSS, Svelte, Sapper, Bootstrap, Foundation, HTML5, Storybook React, Tailwind CSS, jQuery, JavaScript, Responsive Web Design, Git, GitHub, and Bitbucket. Also, I am familiar with WebSocket, Docker, JWT, REST API, and backend API development (CRUD operation) with NestJS. I still enthusiastically grubbing onto any other Front-end technologies/frameworks.
Updated on June 04, 2022Comments
-
Sonjoy Datta almost 2 years
I working with localStorage token in my next.js application. I tried to get the localStorage on page getInitialProps but, it returns
undefined
.Here is an example,
Dashboard.getInitialProps = async () => { const token = localStorage.getItem('auth'); const res = await fetch(`${process.env.API_URL}/pages/about`, { headers: { 'Authorization': token } }); const data = await res.json(); return { page: data }; }