Search code examples
local-storagegatsbyzustand

Problems using localStorage with Gatsby & Zustand-persist?


I am using Zustand in my Gatsby app to manage global state, one of my slices syncs with local storage using zustand-persist. I didnt catch what caused Gatsby to start failing (maybe updated dependency?) but now i get the following error when running gatsby build: WebpackError: ReferenceError: localStorage is not defined

Here is my code:

import create from 'zustand'
import { configurePersist } from 'zustand-persist';

const { persist, purge } = configurePersist({
  storage: localStorage
})

I tried:

import { create } from 'zustand'
import { configurePersist } from 'zustand-persist';

const isBrowser = typeof window !== "undefined";

const { persist, purge } = configurePersist({
  storage: isBrowser ? window?.localStorage : null, // use `AsyncStorage` in react native
  // rootKey: 'root', // optional, default value is `root`
})

But am getting this error: TypeError: Cannot read properties of null (reading 'getItem')

Do I need to actually mock these methods out so it doesnt break the build? Is there no gatsby-specific package to handle this?


Solution

  • You could do something like this so that the function is still available and wont error but it returns null.

    const isBrowser = typeof window !== "undefined";
    const localStorage = isBrowser ? window.localStorage : {
      getItem: () => null,
    }
    
    const { persist, purge } = configurePersist({
      storage: localStorage,
    });