next-persist helps you integrate persistent client-side state with static site generation and server-side rendering with Next.js, allowing the flexibility of building dynamic, isomorphic web applications.
next-persist offers developers a solution for dynamic client-side data persistence without having to worry about the architecture and costs of additional database management systems.
After importing next-persist, simply set up a configuration object and incorporate two functions. We do the rest, delivering you the benefits of SSG and SSR with state persistence.
Simply import
and wrap it around Next.js's Component prop, then wrap Redux's Provider component around
. Set up a configuration object and pass it down to PersistWrapper as the prop
// _app.js
import { Provider } from "react-redux";
import store from "../client/store";
import PersistWrapper from 'next-persist/lib/NextPersistWrapper';
const npConfig = {
method: 'localStorage'
allowList: {
reducerOne: ['stateItemOne', 'stateItemTwo'],
},
};
const MyApp = ({ Component, pageProps }) => {
return (
<Provider store={store}>
<PersistWrapper wrapperConfig={npConfig}>
<Component {...pageProps} />
</PersistWrapper>
</Provider>
);
};
export default MyApp;
In your reducer files, import your storage-retrieval method of choice. Pass your initial state through the next-persist method and set its evaluated result as the default state parameter in your reducer.
// Reducer.js
import { getLocalStore } from 'next-persist'
const initialState = { stateProperty : 'stateValue' };
const persistedState = getLocalStore('state', initialState);
const reducer = (state = persistedState, action) => {
switch (action.type) {
default:
return state;
}
};
If you want to utilize Next.js's server-side rendering feature, import
in the component responsible for data-fetching. Call
within Next.js's data-fetching method and return its evaluated result as the value of the
property on the context object.
// _app.js
import { getCookieProps } from 'next-persist'
const MyApp = ({ Component, pageProps }) => {
return (
<Provider store={store}>
<PersistWrapper wrapperConfig={config}>
<Component {...pageProps} />
</PersistWrapper>
</Provider>
);
};
MyApp.getInitialProps = async ({ ctx }) => {
const cookieState = getCookieProps(ctx);
return {
pageProps : cookieState,
};
};
export default MyApp;