Home > Enterprise >  How to get Laravel CSRF value in NEXTJS
How to get Laravel CSRF value in NEXTJS

Time:10-24

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.

  1. Changed VerifyCsrfToken.php code to disable the csrf protection. (i want to keep the csrf)

  2. Tried adding the csrf cookie using the headers option in Axios. (Axios POST to Laravel API results in 419 error)

  3. Generated key using (PHP artisan key: generate)

  4. Added Session domain

  5. added route in the web middleware

Route::group(['middleware' => ['api']], function () {

    // our routes

});

What's working ?

  1. 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?

CodePudding user response:

Try changing the middleware from web to api.

Route::group(['middleware' => ['api']], function () {

    // our routes

});

CodePudding user response:

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 App\Http\Middleware\VerifyCsrfToken.php class:

<?php namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
  protected $except = [
    'your route here',
  ];
}

CodePudding user response:

I don't know Nextjs, but basically you can put Laravel CSRF token at HTML document meta tag like this

<meta name="csrf-token" content="{{ csrf_token() }}" />

then you can access it using plain javascript like this

var csrf = document.querySelector('meta[name="csrf-token"]').content;
  • Related