Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 };
}
like image 300
Sonjoy Datta Avatar asked Jan 17 '26 08:01

Sonjoy Datta


1 Answers

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.

like image 51
hangindev.com Avatar answered Jan 20 '26 05:01

hangindev.com



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!