skip to Main Content

I got following erros in my next.js 13 project please help me to fix this problem.

[1] - error srcreduxstore.js (12:15) @ localStorage 
[1] - error ReferenceError: localStorage is not defined

this is how it looks in my terminal

enter image description here

this is my store.js file

`import { createStore, combineReducers, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import { rootReducer } from "./rootReducer";

const finalReducer = combineReducers({
  rootReducer,
});

const intialState = {
  rootReducer: {
    cartItems: localStorage.getItem("cartItems")
      ? JSON.parse(localStorage.getItem("cartItems"))
      : [],
  },
};

const middleware = [thunk];

const store = createStore(
  finalReducer,
  intialState,
  composeWithDevTools(applyMiddleware(...middleware))
);

export default store;`

please help me to fix this error

2

Answers


  1. Follow this link, there’s something related:

    Solve ReferenceError: localStorage is not defined in Next.js

    Login or Signup to reply.
  2. Maybe it’s just a hydration issue? Window.localstorage is a browser reserved variable but not so for server. Couldn’t you just give a default value that both server and browser can consume and then once browser loads you update the variable? ( for example with a useEffect )

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search