Next.js: How to access localStorage?

Viewed 5387

I'm currently working on my first member area with next.js. For now I want to store some data in localStorage (token, expiresAr, userInfo) - btw, later this is going to be stored in http-only cookie.

With the following code I get the error: "LocalStorage is not defined":

const AuthProvider = ({ children }) => {
   
   const token = localStorage.getItem("token");
   const userInfo = localStorage.getItem("userInfo");
   const expiresAt = localStorage.getItem("expiresAt");
   

  const [authState, setAuthState] = useState({
    token,
    expiresAt,
    userInfo: userInfo ? JSON.parse(userInfo) : {},
  });

  const setAuthInfo = ({ token, userInfo, expiresAt }) => {
    localStorage.setItem("token", token);
    localStorage.setItem("userInfo", JSON.stringify(userInfo));
    localStorage.setItem("expiresAt", expiresAt);

    setAuthState({
      token,
      userInfo,
      expiresAt,
    });
  };

I already tried to use the following snipped:

if (typeof window !== 'undefined') {
const token = localStorage.getItem("token");
const userInfo = localStorage.getItem("userInfo");
const expiresAt = localStorage.getItem("expiresAt");}

But with this code I get the error "token is undefined". So I tried to define the variables const token, const userInfo and const expiresAt globally. But then I get the error: "Unexpected token o in JSON at position 1".

I'm a little stuck with this problem, so any help is appreciated! Thanks!

2 Answers

This snippet should work

if (typeof window !== 'undefined') {
  const token = localStorage.getItem("token");
  const userInfo = localStorage.getItem("userInfo");
  const expiresAt = localStorage.getItem("expiresAt");
}

The reason you're getting the error token is undefined or unexpected token is because either there is no key token in your localStorage yet or your value is improperly set.

After playing a little bit more with the code and with the help of you guys, I found the solution:

const AuthProvider = ({ children }) => {
  let token = "";
  let userInfo = "";
  let expiresAt = "";

  if (typeof window !== "undefined") {
    token = localStorage.getItem("token");
    userInfo = localStorage.getItem("userInfo");
    expiresAt = localStorage.getItem("expiresAt");
  }

...

The if-statement tells to run the code, when the window is available. I also had to define the variables (let token, let expiresAt and let userInfo) outside of the if-statement in order to be able to access them in other parts of the code.

Maybe this is helpful for somebody..

Related