Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I handle CSRF tokens when integrating a Laravel API with a Node.js client
    Laravel CSRF


How do I handle CSRF tokens when integrating a Laravel API with a Node.js client


To handle CSRF tokens when integrating a Laravel API with a Node.js client, you can follow these steps:

Step 1: Configure Laravel for CSRF Protection

1. Enable CSRF Protection:
- In your Laravel application, ensure that CSRF protection is enabled by setting `protect` to `true` in the `VerifyCsrfToken` middleware:

php
     protected $except = [
         'stripe/*',
         'https://example.com/foo/bar',
         'https://example.com/foo/*',
     ];
     

2. Generate CSRF Tokens:
- Laravel generates a CSRF token for each active user session. You can access this token via the `csrf_token` helper function:

php
     $token = csrf_token();
     

Step 2: Send CSRF Tokens with Requests

1. Include CSRF Tokens in Requests:
- When making requests to your Laravel API from your Node.js client, include the CSRF token in the request headers. For example, using Axios:

javascript
     axios.get('/api/items', {
         headers: {
             'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
         },
     });
     

2. Use Axios with Credentials:
- Ensure that Axios sends cookies with each request by setting `withCredentials` to `true`:

javascript
     axios.get('/api/items', {
         headers: {
             'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
         },
         withCredentials: true,
     });
     

Step 3: Validate CSRF Tokens

1. Validate CSRF Tokens in Laravel:
- In your Laravel API controller, validate the CSRF token in the request headers:

php
     public function index(Request $request)
     {
         if (!$request->hasValidCsrfToken()) {
             return response()->json(['error' => 'CSRF token mismatch'], 419);
         }
         // Process the request
     }
     

Conclusion

By following these steps, you can effectively handle CSRF tokens when integrating a Laravel API with a Node.js client. This ensures that your application remains secure and protected against cross-site request forgery attacks.

Citations:
[1] https://laravel.com/docs/11.x/csrf
[2] https://www.reddit.com/r/laravel/comments/vug5ez/csrf_token_mismatch_when_trying_to_access_laravel/
[3] https://www.stackhawk.com/blog/react-csrf-protection-guide-examples-and-how-to-enable-it/
[4] https://laracasts.com/discuss/channels/laravel/validate-csrf-token-on-api-controller-for-spa
[5] https://github.com/laravel/sanctum/issues/41