Skip to content

A sample project demonstrating how to customize request headers in SSR scenario

Notifications You must be signed in to change notification settings

urhot/nextjs-rtk-query-ssr

Repository files navigation

This is a Next.js project bootstrapped with create-next-app.

What is this?

This project is a sandbox to demonstrate how to customize request headers in SSR api calls.

The premise is that you need to add some authentication headers to your outgoing API calls, and you need some information from the original request to build the necessary headers.

graph TD
    A([User]) -->|Cookie: foo=bar| B(API)
    A -->|Cookie: foo=bar| C[SSR] -->|Cookie: foo=bar| B
Loading

With this example, you can write a prepareHeaders function, where you can

  • Do nothing if running on browser
  • Read cookies or other stuff from request
  • Prepare new cookies to use on the axios request

All this logic can be kept in one place, so your actual RTK use remains clean:

createApi endpoint:

getTodos: builder.query<Todo[], void>({
  query: (): AxiosBaseQueryArgs => ({ url: 'todos/', method: 'get' }),
  providesTags: ['Todos'],
}),

Page component:

const { data } = useGetTodosQuery();

getServersideProps:

store.dispatch(getTodos.initiate());
await Promise.all(getRunningOperationPromises());

Running

To run the development server:

nvm use
npm run dev

Open http://localhost:3505 with your browser to see the result.

Learn More

Technologies used:

About

A sample project demonstrating how to customize request headers in SSR scenario

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published