Reference Error: localStorage is not defined in Next.js

By Hemanta Sundaray on 2022-12-24

Let’s say you have a component like this in your Next.js project:

Import React from "react";
import Link from "next/link";

const Home = () => {

 const name = localStorage.getItem("displayName") || null;

  return (
    <>
      <div>
        {!name && (
            <Link href="/users/sign-in">
              <button>
                Sign In
              </button>
            </Link>
        )}
      </div>
      <div>
        {name && (
          <button
            onClick={handleSignOut}
          >
            Sign Out
          </button>
        )}
      </div>
    </>
  );
};

export default Home;

If you try to render this component, you will get the following error:

ReferenceError: localStorage is not defined

You get this error because the localStorage object is not available on the server-side in a Next.js app. localStorage is a client-side feature.

Solution 1

To fix this error, you can move the code that uses localStorage to a useEffect hook. This way, the code will run after the component is mounted (that is added to the DOM).

Now, we can rewrite our component as shown below:

import { useEffect, useState } from "react"

const Home = () => {
  const [name, setName] = useState(null)

  useEffect(() => {
    setName(localStorage.getItem("displayName") || null)
  }, [])

  // the rest of your component code goes here...
}

This will ensure that the code that uses localStorage is only executed on the client-side, and the error will be fixed.

Solution 2

Alternatively, you could also use the window object to check if the code is being executed on the client or the server.

Here is an example of how you can do this:

import React from "react"

const Home = () => {
  const name =
    typeof window !== "undefined" ? localStorage.getItem("displayName") : null

  // the rest of your component code goes here...
}

This will check if the window object is defined (which is only the case on the client-side) and use localStorage if it is, or use null if it is not defined (which would be the case on the server-side).

Join the Newsletter