Laravel With inertiajs-react get 419 Error (Page expired) when trying to make a POST request from the client to the server.
When making a POST request from the client to the server using Laravel and InertiaJS-React, you might encounter a 419 Error (Page expired) issue. This error typically occurs when the server expects a fresh CSRF token, but the client sends an expired or invalid token.
To resolve this issue, follow the steps below:
- Check the CSRF token in your JavaScript code:
First, ensure that you have properly implemented the CSRF token in your JavaScript code using InertiaJS. In your app/Http/Kernel.php
file, make sure that the 'react'
service provider is registered in the $routeMiddleware
array:
protected $routeMiddleware = [
// ...
'csrf' => \Illuminate\Routing\Middleware\CSRF::class,
];
Then, in your resources/js/app.js
file, import the CSRF token and include it in the headers of your axios requests:
import axios from 'axios';
import token from '@/utils/token';
const api = axios.create({
baseURL: process.env.MIX_API_URL,
headers: {
'X-CSRF-TOKEN': token.getToken(),
},
});
export default api;
Make sure that you have the @/utils/token.js
file, which contains the function to get the CSRF token:
// resources/js/utils/token.js
export function getToken() {
return document.head.querySelector('meta[name="csrf-token"]')?.content || '';
}
- Check the CSRF token in your InertiaJS components:
In your InertiaJS components, make sure that you are using the useForm
or usePage
hook and passing the CSRF token to the post
method:
// resources/js/Pages/YourComponent.js
import { useForm } from '@inertiajs/react';
export default function YourComponent({ initialData }) {
const { data, post, processing, errors } = useForm({
// Your form data here
});
const submit = (e) => {
e.preventDefault();
post(route('your-route'), {
// Your form data here
});
}
return (
<form onSubmit={submit}>
{/* Your form elements here */}
</form>
);
}
- Check the CSRF token in your Laravel routes:
Make sure that you have the CSRF token middleware applied to the route that you are trying to make the POST request to:
// routes/web.php
Route::post('/your-route', function () {
// Your route logic here
})->middleware('csrf');
- Check the CSRF token in your Laravel forms:
Make sure that you have the CSRF token included in your Laravel forms:
// resources/views/your-view.blade.php
<form method="POST" action="/your-route">
@csrf
<!-- Your form elements here -->
</form>
By following these steps, you should be able to resolve the 419 Error (Page expired) issue when making a POST request from the client to the server using Laravel and InertiaJS-React.