Laravel Sanctum with SPA: Best practice for setting the CSRF cookie

Viewed 953

Currently, my SPA is simple and has only a contact form. The form data is sent to the backend. I have installed Laravel Sanctum for that.

axios.get('/sanctum/csrf-cookie').then((response) => {
     axios.post('api/contact')
          .then((response) => {
              //doing stuff
          });
});

This works perfectly fine. However, I was wondering. Where and which time in your SPA do you fire the initial request to get the CSRF cookie? (axios.get('/sanctum/csrf-cookie'))

My first thoughts were:

  • Every time the page is mounted/loaded
  • Only when you receive a 419 and you attempt to refresh the token and retry the previous request
  • You don't fire any API requests, only when the user tries to log in and only then you are requesting a cookie (in my case I don't have any user authentification)
  • For each API request, you wrap it with axios.get('/sanctum/csrf-cookie') around
1 Answers

So for future readers, I chose:

Only when you receive a 419 and you attempt to refresh the token and retry the previous request

For that, I'm using the package axios-auth-refresh.

My settings look like that

//bootstrap.js

import axios from 'axios';
import createAuthRefreshInterceptor from 'axios-auth-refresh';

axios.defaults.withCredentials = true;
axios.defaults.baseURL = process.env.GRIDSOME_BACKEND_URL;

const refreshAuthLogic = (failedRequest) => axios.get('/sanctum/csrf-cookie').then((response) => Promise.resolve());

createAuthRefreshInterceptor(axios, refreshAuthLogic, { statusCodes: [419] });

window.axios = axios;
Related