logo
next-persist-logo
A Node module by most.js
Bridging the gap between client-side persistence and server-side rendering.

State persistence with Next.js

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.

Lightweight solution

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.

Declarative and semantic

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.

Importing PersistWrapper

Simply import PersistWrapper and wrap it around Next.js's Component prop, then wrap Redux's Provider component around PersistWrapper. Set up a configuration object and pass it down to PersistWrapper as the prop wrapperConfig

// _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;

Retrieving persisted state from the client

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;
  }
};

Server-side rendering with next-persist

If you want to utilize Next.js's server-side rendering feature, import getCookieProps in the component responsible for data-fetching. Call getCookieProps within Next.js's data-fetching method and return its evaluated result as the value of the pageProps 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;

The team behind most.js

Headshot of Brian
Headshot of Christopher
Headshot of Greg
Headshot of Matt
next-persist-logo

A node module by most.js