How To Exclude a URL from CSRF in Laravel 11

CSRF (Cross-Site Request Forgery) is a security vulnerability that can be exploited to execute unauthorized actions on a web application. Laravel provides built-in CSRF protection to mitigate this risk. However, there are times when you might need to exclude certain routes from CSRF checks, such as for external APIs or specific actions that don’t require CSRF protection.

in this post, i will show you how to disable CSRF token in Laravel 11:

VerifyCsrfToken Middleware file is removed in Laravel 11, so now you need to add validateCsrfTokens in bootstrap/app.php

Here’s how to exclude a url checks from Laravel 11 onwards.

Start by opening the bootstrap/app.php file for your project. Here, you’ll see a withMiddleware method is invoked, with the option to customise this with a callback.

->withMiddleware(function (Middleware $middleware) {
//
})

To exclude any routes from CSRF checks, chain onto the Middleware object with the validateCsrfTokens and provide the except parameter:

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: [
        'domain.com/page-url/*',
    ]);
})

Here, we’re using a wildcard to exclude any routes that start with stripe/, but you can also provide set paths.

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: [
        'stripe/webhook',
    ]);
})

While this method of excluding routes from CSRF tokens has changed since Laravel 10, it’s allowed for the removal of the VerifyCsrfToken middleware in previous versions to provide a cleaner boilerplate.

Leave a Reply

Your email address will not be published. Required fields are marked *