Skip to content

Instantly share code, notes, and snippets.

@mqnoy
Last active August 20, 2024 00:20
Show Gist options
  • Save mqnoy/df5ea099dc98d9a79cd21fbb02632b1e to your computer and use it in GitHub Desktop.
Save mqnoy/df5ea099dc98d9a79cd21fbb02632b1e to your computer and use it in GitHub Desktop.
Redux-Persist with Next.js 14 App Router

regarding the issue redux-persist failed to create sync storage. falling back to noop storage i found the solution for implementing redux-persist on NextJS with approuter

currently i'm using:

"next": "14.2.5",
"redux-persist": "^6.0.0",
"react-redux": "^9.1.2",
"@reduxjs/toolkit": "^2.2.6",

ssr-safe-storage.ts

'use client';

import createWebStorage from 'redux-persist/lib/storage/createWebStorage';

interface NoopStorageReturnType {
  getItem: (_key: any) => Promise<null>;
  setItem: (_key: any, value: any) => Promise<any>;
  removeItem: (_key: any) => Promise<void>;
}

const createNoopStorage = (): NoopStorageReturnType => {
  return {
    getItem(_key: any): Promise<null> {
      return Promise.resolve(null);
    },
    setItem(_key: any, value: any): Promise<any> {
      return Promise.resolve(value);
    },
    removeItem(_key: any): Promise<void> {
      return Promise.resolve();
    },
  };
};

const storage =
  typeof window !== 'undefined'
    ? createWebStorage('local')
    : createNoopStorage();

export default storage;

StoreProvider.tsx

'use client';

import { useRef } from 'react';
import { Provider } from 'react-redux';
import { makeStore, AppStore } from '@/lib/redux/store';
import { Provider as JotaiProvider } from 'jotai';
import { PersistGate } from 'redux-persist/integration/react';
import { type Persistor, persistStore } from 'redux-persist';

export default function StoreProvider({
  children,
}: React.PropsWithChildren<{}>) {
  const storeRef = useRef<AppStore>();
  const persistorRef = useRef<Persistor>({} as Persistor);
  if (!storeRef.current) {
    storeRef.current = makeStore();
    persistorRef.current = persistStore(storeRef.current);
  }


  return (
    <Provider store={storeRef.current}>
      <PersistGate loading={null} persistor={persistorRef.current}>
        {children}
      </PersistGate>
    </Provider>
  );

}


source :

https://stackoverflow.com/questions/77783551/how-to-use-redux-persist-with-next-js-app-router

vercel/next.js#15687

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment