I have a Next JS frontend and Laravel 9 as backend. Created APIs and tested them on the postman. All of the API’s working fine without any issues.
The Problem
So I have created a Nextjs file with a form and posted data using Axios. I am getting Error: Request failed with status code 419
.
Tried
There are multiple answers available on StackOverflow for similar questions. I followed the answers but nothing worked for the problem.
-
Changed VerifyCsrfToken.php code to disable the csrf protection. (i
want to keep the csrf) -
Tried adding the csrf cookie using the headers option in Axios.
(Axios POST to Laravel API results in 419 error) -
Generated key using (PHP artisan key: generate)
-
Added Session domain
-
added route in the web middleware
Route::group(['middleware' => ['api']], function () {
// our routes
});
What’s working ?
- Allowing all domains in VerifyCsrfToken.php is working.
I want to get csrf token
`const csrf = () => axios.get(‘/sanctum/csrf-cookie’)’
i am getting empty value for csrf token / csrf cookie. and found no accepted answer to the request failed with status code 419.
Does anyone know what I am doing wrong?
4
Answers
As per the documentation of laravel :
Do these 3 changes in Laravel
From :
'supports_credentials' => false,
To:
'supports_credentials' => true,
axios.defaults.withCredentials = true;
Now do the following cahnges in NEXT JS app.
Add .env.local file at the root and add the following code.
NEXT_PUBLIC_BACKEND_URL=http://localhost:8000'
Install axios using
npm i axios
Import CSRF Token using AXIOS before posting the data using axios then post form data using axios.
Here is the sample code to send or get data
Note : Pleae change
http://localhost:8000
as your laravle url andhttp://localhost:3000
as per your frontend url.The above solution worked for me.
Try changing the middleware from
web
toapi
.If you don’t have the csrf token in your frontend, and want to disable the check on that specific route, you need to add the route to $except array in your AppHttpMiddlewareVerifyCsrfToken.php class:
I don’t know Nextjs, but basically you can put Laravel CSRF token at HTML document meta tag like this
then you can access it using plain javascript like this