Sonjoy Datta
Sonjoy Datta

Reputation: 1388

Get localStorage in NextJs getInitialProps

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 };
}

Upvotes: 3

Views: 24494

Answers (1)

hangindev.com
hangindev.com

Reputation: 4873

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. 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.

Upvotes: 5

Related Questions