This is a Next.js project bootstrapped with create-next-app
.
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
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());
To run the development server:
nvm use
npm run dev
Open http://localhost:3505 with your browser to see the result.
Technologies used: