DEV Community

Cover image for Accessing LocalStorage in NextJS
Ibrahim Adeniyi
Ibrahim Adeniyi

Posted on • Updated on

Accessing LocalStorage in NextJS

I recently migrated a Content Management System from Create React App to NextJS in order to score some SEO points.
One of the challenges I faced was seeing these errors at compile time.

window is undefined or document is undefined

Window, and document are not available on the server. This is why you'll run into these types of errors if you are trying to access window properties or document.
In my case, I was persisting my authentication token to localStorage on the previous application.

To avoid running into these undefined errors at compile and build time, you can run a simple check.

if (typeof window !== "undefined") {

localStorage.setItem(key, value)

}
Enter fullscreen mode Exit fullscreen mode

This basically tells your piece of code only to run when it's in the client environment where it can access window.

Keep hacking.

Top comments (13)

Collapse
 
jaloplo profile image
Jaime López

Nice trick, but I think it would make more sense to use useEffect method, did you try it?

useEffect(function() {
    console.log(window.localStorate);
},[]);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
simpleneeraj profile image
Simple Neeraj
useEffect(function() {
    console.log(window.localstorage);
},[]);
Enter fullscreen mode Exit fullscreen mode

Because some time we need to copy and paste code, and after code doesn't work after pasting so developers 😯😯😯😯😯.

Your Code have some mistakes check out this 👍

Collapse
 
dgifted profile image
Justus Okwuchukwu Ali

You may find yourself in a situation where you need access to localStorage outside a react component. In that case useEffect cannot help.

Collapse
 
riper profile image
Magnus Bondesson

window.localStorage (spelling)

Collapse
 
simpleneeraj profile image
Simple Neeraj • Edited

Trying to making a reusable function

This function for get data from localstorage
key is required

const getFromStorage = (key) => {
if(typeof window !== 'undefined'){
     window.localstorage.getItem(key)
}
}
Enter fullscreen mode Exit fullscreen mode

Set data to localstorage

const setToStorage = (key,value) => {
if(typeof window !== 'undefined'){
     return window.localstorage.setItem(key,value)
}
}
Enter fullscreen mode Exit fullscreen mode

Any new method to use window in nextjs

Collapse
 
nduyvu1511 profile image
Vu

That's nice

Collapse
 
cirosantilli profile image
Ciro Santilli

This leads to a warning of type "Expected server HTML to contain a matching" on Next 10 BTW: stackoverflow.com/questions/464436...

Collapse
 
ariyou2000 profile image
ARiyou Jahan • Edited

remember, never create a function for window type checking.
it always must be an explicit type checking or it will not work


Right way to do it:

if (typeof window !== "undefined") {
    // client-side operation such as local storage.
    localStorage.setItem(key, value)
}
Enter fullscreen mode Exit fullscreen mode

Wrong way:

const hasWindow = () => {
    return typeof window !== "undefined"
}

if (hasWindow()) {
    // client-side operation such as local storage.
    localStorage.setItem(key, value)
}

if (!hasWindow()) {
    // server-side code
}
Enter fullscreen mode Exit fullscreen mode

read more and reason for this problem: Next.js GitHub issues page

Collapse
 
othman2001 profile image
Othman

what if i want to access local storage inside redux reducer ?

Collapse
 
atomisadev profile image
Atom

That's nice, but next time add a js tag to the code block to make it more readable.

Example:

if (typeof window !== "undefined") {

localStorage.setItem(key, value)

}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dendekky profile image
Ibrahim Adeniyi

Thank you

Collapse
 
77pintu profile image
77pintu

Thanks for the great post !!!!!!

Collapse
 
bassochette profile image
Julien Prugne

Thanks mate!
Works the same with sessionStorage