Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version
  1. Enable CSRF protection in the backend: This involves adding an XSRF-Token to the cookie/session on every request.

  2. Obtain the XSRF-Token: You can obtain the XSRF token by intercepting an initial request to the server that is protected by CSRF. Most modern web frameworks have a helper function that adds the XSRF token to the response.

  3. Add the XSRF-Token header to RTK Query: The XSRF-Token must be sent to the server with every request as a request header. You can add the header using fetchBaseQuery config object by providing a function that will retrieve the XSRF-Token from the storage.

  4. Verify the XSRF-Token in the backend: When the server receives the request with the XSRF-Token, it should compare this value with the value stored in the cookie/session.

  5. Return a 401 Unauthorized status code: If the XSRF-Token is invalid, the server should return a 401 status code to the client.

To obtain the XSRF-Token, you can use the following code:

const getCsrfToken = async () => {
  const response = await fetch('/api/get-csrf-token');
  const { csrfToken } = await response.json();
  return csrfToken;
};

const api = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: 'https://api.example.com',
    prepareHeaders: (headers, { getState }) => {
      const csrfToken = getState().auth.csrfToken;
      if (csrfToken) {
        headers.set('X-XSRF-Token', csrfToken);
      }
      return headers;
    },
  }),
  endpoints: (builder) => ({
    // ...
  }),
});

const store = configureStore({
  reducer: api.reducerPath,
  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
});

store.dispatch((dispatch) => {
  dispatch(api.util.setMatchedEndpoints());
  dispatch(getCsrfToken()).then((csrfToken) =>
    dispatch({ type: 'auth/csrfTokenReceived', payload: csrfToken })
  );
});