Skip to content

Axios CSRF header configuration doesn't work #40

@Mado13

Description

@Mado13

Description

When using Inertia.js with Phoenix, setting axios.defaults.xsrfHeaderName doesn't affect the CSRF header sent with Inertia requests.

Problem

According to the documentation, setting axios.defaults.xsrfHeaderName = "x-csrf-token" should configure Axios to send the CSRF token with the header name that Phoenix expects. However, Inertia continues to send the token as x-xsrf-token instead, causing Phoenix's CSRF protection to reject the requests

Reproduction Steps

Configure Axios in app.js:

import axios from "axios";
axios.defaults.xsrfHeaderName = "x-csrf-token";

Initialize Inertia app as normal
Submit a form using Inertia's useForm to a Phoenix endpoint
Observe in the network tab that the request includes x-xsrf-token header but not x-csrf-token

Expected Behavior

The CSRF token should be sent with the x-csrf-token header as configured in the Axios defaults.

Actual Behavior

The CSRF token is sent with the x-xsrf-token header regardless of the Axios configuration.

Workaround

I was able to work around this issue by intercepting Inertia's requests and manually changing the header:

Inertia.on('before', (event) => {
  const getCookieValue = (name) => {
    const cookies = document.cookie.split('; ');
    for (const cookie of cookies) {
      const [cookieName, cookieValue] = cookie.split('=');
      if (cookieName === name) {
        return decodeURIComponent(cookieValue);
      }
    }
    return null;
  };

  const token = getCookieValue('XSRF-TOKEN');
  
  if (token) {
    event.detail.visit.headers['x-csrf-token'] = token;
    delete event.detail.visit.headers['x-xsrf-token'];
  }
});

Environment

Inertia.js: 2.3.0
Phoenix: 1.7.0
Svelte: 5

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions