localStorage is not defined in next js – Javascript

by
Ali Hasan
local-storage next.js react-redux reactjs

Quick Fix: Check if window is defined before accessing localStorage. Use optional chaining or useEffect hook to handle this scenario in React.

The Solutions:

Solution 1: Check window is defined

Since server-side rendering in Next.js does not have a `window` object, you can check if it exists before accessing `localStorage`:

if (typeof window !== 'undefined') {
  const getUserfromLocalStorage = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null;
}

Solution 2: Optional Chaining

You can use optional chaining (?.) to access `localStorage` only if the `window` object exists:

const getUserfromLocalStorage = window?.localStorage?.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null;

Solution 3: useEffect

React’s `useEffect` can be used to perform actions when the component mounts (or updates):

import { useEffect } from "react";

useEffect(() => {
  const getUserfromLocalStorage = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null;
}, []);

Solution 2: Use optional chaining on the global object

This solution provides a more robust way to check for the presence of the window object, even in cases where it is not explicitly defined.

By using the optional chaining operator ?. on the global object, you can safely access the window object and its properties, even if they do not exist.

The code snippet below illustrates this approach:

if (global?.window !== undefined) {
  // Now it's safe to access window and localStorage
  localStorage.setItem('token', token);
}

Solution 3: Use JSON.parse() with default value

Instead of directly accessing localStorage.getItem("user"), use JSON.parse(localStorage.getItem("user") || "{}") || null. This ensures that you have a valid JSON object to work with, even if the "user" key doesn’t exist in localStorage. Here’s the modified code:

const localStorageData = JSON.parse(localStorage.getItem("user") || "{}") || null;

const initialState = {
  user: localStorageData,
  // Rest of the state remains the same
};

Q&A

As Next.js is server side rendering I can’t get localStorage. What should I do to get localStorage?

You can use optional chaining on the global object to access the window object.

I am still getting ReferenceError: window is not defined when I check on the window object.

You can use optional chaining on the global object to access the window object.

Video Explanation:

The following video, titled "LocalStorage Next.js - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Learn how to get query paramets from the url and then save them into LocalStorage in Next.js Starter code: Server: ...