Cannot get persisted redux store data in Next.js 13 (page router) with custom redux-persist cookie storage

247 Views Asked by At

In my Next.js 13 (page router) app, I have used the cookies-next package to create a custom storage for redux-persist since the default storage (i.e. localStorage) used by redux-persist cannot be accessed on the server-side:

import { WebStorage } from 'redux-persist';
import { getCookie, setCookie, deleteCookie } from 'cookies-next';

const storage: WebStorage = {
    getItem: async (key) => getCookie(key) || null,
    setItem: async (key, item) => setCookie(key, item),
    removeItem: async (key) => deleteCookie(key),
};

export const persistConfig = {
    key: 'my-app',
    version: 1,
    storage,
};

Then created and used the redux store with next-redux-wrapper in the following way:

//authSlice.ts
export interface AuthState {
    user: User|null;
    token: string;
}

export const authSlice= createSlice({
  name: 'auth',

  initialState: {
   token:'',
   user: null,
  } as AuthState,

  reducers: {
    //rest of code
  },

  extraReducers(builder) {
        builder.addCase(HYDRATE, (state, action: AnyAction) => {
            const nextState = {
                ...state,
                ...action.payload.auth,
            };
            return nextState;
        });
   },
});

//store.ts
export const rootReducer = combineReducers({
    [authSlice.name]: authSlice.reducer,
    // rest of the redux slices
});

const persistedReducer = persistReducer(persistConfig, rootReducer);

const store = configureStore({
    reducer: persistedReducer,
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
            serializableCheck: {
                ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
            },
        }).concat(apiSlice.middleware),
    devTools: true,
});

const makeStore = () => store;
export type AppStore = ReturnType<typeof makeStore>;
export type AppDispatch = AppStore['dispatch'];

export const reduxWrapper = createWrapper<AppStore>(makeStore, { debug: false });
export const persistor = persistStore(store);

//_app.tsx
import React, {FC} from 'react';
import {Provider} from 'react-redux';
import {AppProps} from 'next/app';
import { reduxWrapper, persistor } from '@/redux/store';

const MyApp: FC<AppProps> = ({Component, ...rest}) => {
  const {store, props} = reduxWrapper.useWrappedStore(rest);
  return (
    <Provider store={store}>
            <PersistGate loading={null} persistor={persistor}>
               <Component {...props.pageProps} />
            </PersistGate>
    </Provider>
  );
};

export default MyApp;

However, I am not getting the cookie neither from server or client side. Is there is any issue in configuration or is there some other solution for this?

0

There are 0 best solutions below