DEV Community

Cover image for How to use Local Storage in Next.js

How to use Local Storage in Next.js

collegewap on April 09, 2023

Have you received the following error while using local storage in Next.js? ReferenceError: localStorage is not defined Enter full...
Collapse
 
prems5 profile image
PREM KUMAR • Edited

from next js 13 you must use

'use client'
Enter fullscreen mode Exit fullscreen mode

on top of the file

and it will work without any error and it's more cleaner solution

Collapse
 
professor12 profile image
Badejo Emmanuel Adewale

It will have an error in development mode since the component would still run on the server

Collapse
 
pablojsx profile image
Pablojsx

does 'use client' works with nextjs pages? I'm a bit confused

Collapse
 
prems5 profile image
PREM KUMAR

Yes, it works on the new routes folder. Where all the components are server components by default. You need to specify use client
To make it as a client side component

Thread Thread
 
pablojsx profile image
Pablojsx

sorry I mean pages router not nextjs pages, is it an app router thing only?

Collapse
 
mmvlad profile image
Vladyslav Melnychenko

This must be a joke.

How bad the framework needs to be if you can't use localstorage in 1 line of code.

Collapse
 
lmish profile image
lmish

How good framework needs to be if you can use local storage with a server side rendering.

Collapse
 
pickyourdestiny profile image
pickyourdestiny • Edited

I think conceptually its important to understand that you need to save the form data to local storage when the form field data changes during a client event (like submitting the form or making changes to form fields). With pure react you were able to update local storage using useEffect when the form object changes but this wont work in NextJS because the form object will clear (and hence nullify form fields in local storage) on initial component load before hydrating the client.

Takeaway approach (which is provided in this article): One useEffect to retrieve the local storage value if local storage is populated, and only write to local storage during a client event.

Collapse
 
vulcanwm profile image
Medea

really helpful post!

Collapse
 
muhammadasif_wd profile image
Muhammad Asif

Thanks for this. working code.

Collapse
 
alisina123 profile image
Alisina Sadat

how to use Middle ware localstorage ?

Collapse
 
reddash99 profile image
RedDash99

Thank you for the useful hook, it works perfectly!

Collapse
 
prat1kgupta profile image
pratik gupta

custom hook method is not working🥲

Collapse
 
collegewap profile image