Search code examples
reactjslaravelaxioscsrflaravel-sanctum

Laravel Sanctum with Redux Toolkit & Axios


I have a backend with laravel sanctum implementation, all config are working correctly. On the frontend I use react, an action is dispatched to login, for example. X-XSRF-TOKEN must be set before hitting the endpoint, thus I must call /sanctum/csrf-cookie first, I've ran into these problems:

  1. If I try and get the csrf token in createAsyncThunk first, and then /login, redux toolkit assumes the request is fulfilled, thus changing the state before the login api is called
  2. I have no idea why when I create an axios instance, the X-XSRF-TOKEN is not being set in the header, but when I use axios imported normally, it works.

Action

export const login = createAsyncThunk("auth/login", async (_) => {
  try {
    request.get("sanctum/csrf-cookie").then((response) => {
      // THE PROBLEM OCCURS HERE, no header is received, (request is instantiated below, if I import axios it works)
      const res = await request.post("/login", _);
      return res.data;
      // this one failed with 419 csrf token mismatch, eventually because X-XSRF-TOKEN is not set, im not sure why
    });
  } catch (err) {
      throw err;
  }
});

axios

import axios from "axios";

export const  request = axios.create({
  baseURL: `http://localhost:8000/`,
   headers: {
     Accept: "application/json",
  },
});

axios.defaults.withCredentials = true;

Note: The backend is working and configued correctly, because if I do not create an instance and just import and use axios, the request is working, but I'm back with problem 1, where the thunk is fulfilled on the first request (before return response.data), and i'm not interested in such a solution, I don't need to copy the code

Summary: The sanctum/csrf-cookie response has no X-XSRF-TOKEN header, only when creating an axios instance using axios.create, a cookie is received though Perhaps the header is resetting to its default on the second request? how can I append the headers from the first request? Thanks

-- Should I try instead of calling sanctum/csrf-cookie in all requests like this, intercept the request and somehow append the header to the request?

Any help, examples, guides are appreciated


Solution

  • rookie mistake, was using axios.defaults.withCredentials = true; instead of axiosInstance.defaults.withCredentials = true;