Blog>
Snippets

Initializing a Redux Store for SSR in Next.js

Demonstrate how to configure a Redux store in Next.js with server-side rendering, including checks to ensure a single store instance per request.
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { createWrapper } from 'next-redux-wrapper';

// initialState for the Redux store
const initialState = {};

// Your root reducer
const rootReducer = (state = initialState, action) => {
  // Your reducer logic here
  return state;
};

// Function to create a store
const makeStore = (context) => {
  const store = createStore(rootReducer);
  return store;
};

// Export an HOC which wraps the given component with Provider
export const wrapper = createWrapper(makeStore, { debug: true });
This code creates a Redux store using `createStore` from Redux and connects it to the Next.js application with Next Redux Wrapper's `createWrapper`. The `makeStore` function ensures a new instance of the store is created per request.
import { wrapper } from './store';

// Your Next.js App or Page component
const MyApp = ({ Component, pageProps }) => (
  <Provider store={store}>
    <Component {...pageProps} />
  </Provider>
);

// Connect the Next.js App with the Redux store
export default wrapper.withRedux(MyApp);
This code snippet shows how to wrap your Next.js App component with the Redux Provider using the wrapper created by 'next-redux-wrapper'. This connects the Redux store with the App.