Server Side Rendering

RTK Query supports Server Side Rendering (SSR) with Next.js via rehydration with next-redux-wrapper.

You should, in getStaticProps or getServerSideProps:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' import { HYDRATE } from 'next-redux-wrapper' export const api = createApi({ baseQuery: fetchBaseQuery({ baseUrl: '/' }), extractRehydrationInfo(action, { reducerPath }) { if (action.type === HYDRATE) { return action.payload[reducerPath] } }, endpoints: (build) => ({ // omitted }), })

If you are not using Next.js, you should define another version of createApi({}):

import { buildCreateApi, coreModule, reactHooksModule, } from '@reduxjs/toolkit/query/react' const createApi = buildCreateApi( coreModule(), reactHooksModule({ unstable__sideEffectsInRender: true }) )

...and wait for all queries to finish using await Promise.all(api.util.getRunningOperationPromises()) before performing the next render cycle.

API state rehydration can be used in conjunction with Redux Persist by leveraging the REHYDRATE action type imported from redux-persist. This can be used out of the box with the autoMergeLevel1 or autoMergeLevel2 state reconcilers when persisting the root reducer, or with the autoMergeLevel1 reconciler when persisting just the api reducer.

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' import { REHYDRATE } from 'redux-persist' export const api = createApi({ baseQuery: fetchBaseQuery({ baseUrl: '/' }), extractRehydrationInfo(action, { reducerPath }) { if (action.type === REHYDRATE) { return action.payload[reducerPath] } }, endpoints: (build) => ({ // omitted }), })