'NextJS localstorage is not defined [duplicate]

How can i fix this? i'm trying to almacenate my cartItems state in the localStorage but nextJs throw me localstorage is not defined error.

const initialState = {
  cartItems: localStorage.getItem("cartItems")
    ? JSON.parse(localStorage.getItem("cartItems"))
    : [],
  cartTotalQuantity: 0,
  cartTotalAmout: 0,
};


Solution 1:[1]

localStorage is defined only in browsers (of course!)

in Next.js, your code is run both in the browser and the server.

You can safely initialize and use your state in useEffect hook like this

function MyComponent() {
  const [myState, setMyState] = React.useState({ cartItems: [], cartTotalQuantity: 0, cartTotalAmount: 0 });

  // This code runs after the component mounted
  React.useEffect(() => {
    const cartItemsString = localStorage.get('cartItems');

    if (cartItemsString) {
      setMyState((prev) => ({ ...prev, cartItems: JSON.parse(cartItemsString) }))
    }
  }, [])

  return <>YOUR JSX GOES HERE</>
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kay Kim