Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

Error “localStorage is not defined” in NextJs – how to fix it

Let's say we want to build a popup component in NextJs that does something based on a value set in the localStorage.

Something like this:

export default function Popup() {
    const status = localStorage.getItem('status')
    // do stuff based on the status here

If we will try to import and use this Popup component in the main layout file:

// app/layout.js
export default function RootLayout({ children }) {
    return (<>
        <Popup />

We will get the below error:

Uncaught Reference Error: localStorage is not defined

screenshot of localStorage is not defined error in NextJS

This happens because, in the app folder, the NextJs components are serverside components where we don't have access to the client-side specific features such as localStorage.

In order to fix the "localStorage is not defined" we need to mark our component as a client component:

'use client'

And after we define our component as a client one we get access also to the React client-side hooks that are perfect for situations such as this one:

'use client'
import {useState, useEffect} from 'react'

export default function Popup() {
    const [status, setStatus] = useState()
    useEffect(() => {
    }, [])

Fixing the "localStorage is not defined" error in versions prior to NextJs 13

In this example, we are working with the app folder that was added in NextJs 13. For versions of NextJs prior 13 we can just do a simple check:

if (typeof window !== 'undefined') {
  // do localStorage stuff here
  const item = localStorage.getItem('key')
Home Screencasts Best of Newsletter Search X