Search code examples
javascriptphplaravellaravel-5csrf

How does Laravel add X-XSRF-TOKEN automatically when requesting via axios?


I have a API that uses the same auth middleware. So when I am successfully logged in, I am redirected to a page that gets data from my API from the same app. In my app.blade.php I only have axios added and a simple html and take note, I don't even have a csrf-token meta in my header except from my login page which has @csrf in my form.

Here is my app.blade.php layout

<html lang="en">
<head>
  <meta charset="UTF-8">
</head>
<body>
  @yield('content')

  <script src="{{ asset('js/axios.min.js') }}"></script>
  <script>
    const http = axios.create({
      baseURL: '/api'
    });

    http.interceptors.request.use((request) => {
      console.log('Starting Request', request);
      return request;
    });
  </script>

  @stack('scripts')
</body>
</html>

and in one of my pages:

@extends('layouts.app')

@section('content')
<div>
  <h1>Hello World</h1>
</div>
@endsection

@push('scripts')
<script>
  async function test() {
    const { data } = await http('/some-page');

    // I'm getting a data even without passing a csrf token?
    console.log(data);
  }

  test();
</script>
@endpush

I'm getting the API data even without passing a csrf/xsrf token which is weird.

When I check my console for logs of outgoing request, this is the output

enter image description here

I mean, where did that came form? I don't even have a csrf token in my templates and also nothing or whatsoever passed to my axios config.

Am I missing something here?


Solution

  • Check the docs on XSRF token:

    X-XSRF-TOKEN

    Laravel stores the current CSRF token in a XSRF-TOKEN cookie that is included with each response generated by the framework. You can use the cookie value to set the X-XSRF-TOKEN request header.

    This cookie is primarily sent as a convenience since some JavaScript frameworks and libraries, like Angular and Axios, automatically place its value in the X-XSRF-TOKEN header.