Laravel CSRF Token Mismatch and 419 Page Expire Solution
Laravel CSRF Token mismatch and 419 Page Expire error fixing. The stack I’m using was Laravel, Vue, and InertiaJS. I perform this article using Vanilla JS because JQuery $ mostly generates errors like $ is not defined etc…
Table of Contents
This article
- Laravel
- Vue
- Inertia JS
- Laravel Passport + Sanctum
- Uppy.io for media upload (dropzone, or filepond etc.)
1. How to Fix CSRF token issue using JavaScript (without jQuery)
Error I was facing.
- 419 PAGE EXPIRED
- message : “CSRF token mismatch.”, exception: “Symfony\Component\HttpKernel\Exception\HttpException”
Route file, Route is protected with auth:sanctum
middleware in web.php
Route::post('/media/upload', MediaController::class)
->middleware('auth:sanctum')
->name('media.upload');
2. Add meta tag for CSRF token in app.blade.php
Add <meta name="csrf-token" content="{{ csrf_token() }}">
in app.blade.php
<meta name="csrf-token" content="{{ csrf_token() }}">
3. Get CSRF Token Value using JavaScript and append in Headers
Get the csrf-token value using javascript.
headers: {
"Accept": "application/json",
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
},
"Accept": "application/json"
for 419 PAGE EXPIRED fixing.
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
for CSRF token mismatch fixing.
It worked whether you are using Axios, Ajax, XHR, uppy.io XHRUpload, or SPA
$.ajax({
type:'POST',
url:'/hassam.dev/media/upload',
headers: {
"Accept": "application/json",
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
},
});
How to get meta CSRF token value using Vanilla JavaScript?
Make sure your file must have meta value e.g <meta name="csrf-token" content="maZJl7Q...">
let token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
How to fix Laravel 419 error for Uppy.io file upload.
Error while uploading files using Uppy.io XHR Upload or Uppy.io Dashboard a 419 Page Expire error occurred or CSRF Token mismatch error fixing.
import Uppy from '@uppy/core'
import { Dashboard } from '@uppy/vue'
import XHRUpload from '@uppy/xhr-upload'
uppy: () => new Uppy()
.on('complete', result => {
console.log('successful files:', result.successful)
console.log('failed files:', result.failed)
})
.use(XHRUpload, {
headers: {
"Accept": "application/json",
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
},
endpoint: route("media.upload"),
formData: true,
fieldName: 'files[]',
})
Uppy JS 419 Page Expire Error Media
Uppy JS 419 Page Expire Error fixing
How to get meta CSRF token value using Vanilla JavaScript?
let token = document.querySelector(‘meta[name=”csrf-token”]’).getAttribute(‘content’);