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 />
            {children}
        </>
  )
}

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(() => {
        setStatus(localStorage.getItem('status'))
    }, [])
}

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')
}

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X