Ehsan Bagherzadegan
Back to articles
6 min read

Laravel 13.40: Precise Middleware Ordering with insertBefore and insertAfter

Laravel 13.40 adds four new methods to insert middleware at exact positions relative to built-in classes — no more copying the entire stack or accepting imprecise prepend/append positioning.

Laravel 13.40 adds four new methods to the middleware configuration API that solve a long-standing annoyance: inserting custom middleware at a precise position relative to a built-in class, without rewriting the entire stack.

The problem with prepend and append

Until now, the global middleware stack and named groups (web, api, custom) only offered two positioning tools:

  • prepend() — adds to the very beginning
  • append() — adds to the very end

If you needed your middleware to run after TrustProxies (so $request->ip() is already correct) but before TrimStrings, you had two bad options:

  1. Copy the entire default stack into bootstrap/app.php, insert your class at the right index, and maintain that list forever.
  2. Use a middleware group and accept that your middleware runs either too early or too late.

Both approaches are fragile. Framework upgrades can add, remove, or rename built-in middleware (for example, ValidateCsrfToken was renamed to PreventRequestForgery in Laravel 12), silently breaking your custom ordering.

The new API

Laravel 13.40 introduces four methods on the Middleware configurator in bootstrap/app.php:

Method Scope Behavior
insertAfter($existing, $new) Global stack Insert $new immediately after $existing
insertBefore($existing, $new) Global stack Insert $new immediately before $existing
insertAfterInGroup($group, $existing, $new) Named group Insert $new after $existing inside $group
insertBeforeInGroup($group, $existing, $new) Named group Insert $new before $existing inside $group

All four methods reference the target middleware by its class string (e.g., TrustProxies::class). If the target class is not present in the stack, the insertion is silently skipped — your middleware simply won't be added. This is intentional: it keeps the configuration resilient when a target middleware is removed by a framework upgrade or by your own remove() call.

Practical examples

1. Block banned IPs after TrustProxies

You want to reject requests from banned IPs, but you need $request->ip() to return the real client IP first. TrustProxies normalizes the IP header; your middleware should run right after it.

use App\Http\Middleware\BlockBannedIps;
use Illuminate\Http\Middleware\TrustProxies;

->withMiddleware(function (Middleware $middleware) {
    $middleware->insertAfter(TrustProxies::class, BlockBannedIps::class);
})

2. Sanitize input before TrimStrings

TrimStrings runs early in the global stack. If you have a SanitizeInput middleware that strips tags or normalizes encoding, it should run before trimming so the trimmed result is already clean.

use App\Http\Middleware\SanitizeInput;
use Illuminate\Foundation\Http\Middleware\TrimStrings;

->withMiddleware(function (Middleware $middleware) {
    $middleware->insertBefore(TrimStrings::class, SanitizeInput::class);
})

3. Set locale from session inside the web group

The web group includes StartSession. If you want to read the user's preferred locale from the session and set it on the application, your middleware must run after the session is started.

use App\Http\Middleware\SetLocaleFromSession;
use Illuminate\Session\Middleware\StartSession;

->withMiddleware(function (Middleware $middleware) {
    $middleware->insertAfterInGroup('web', StartSession::class, SetLocaleFromSession::class);
})

4. Add rate limiting before SubstituteBindings in the api group

SubstituteBindings resolves route model bindings. If you want to rate-limit based on the resolved model (e.g., per-user limits), your rate limiter needs to run after binding substitution but before your controller. Since SubstituteBindings is in the api group by default:

use App\Http\Middleware\RateLimitByUser;
use Illuminate\Routing\Middleware\SubstituteBindings;

->withMiddleware(function (Middleware $middleware) {
    $middleware->insertAfterInGroup('api', SubstituteBindings::class, RateLimitByUser::class);
})

How it works under the hood

The implementation reuses the existing replace() and replaceInGroup() methods, which now accept arrays as the replacement value. When you call insertAfter('target', 'new'), the framework:

  1. Finds the index of target in the stack.
  2. Builds a new array: everything up to and including target, then new, then the rest.
  3. Calls replace() with that array.

This means the insertion is atomic and survives framework upgrades. If Laravel later inserts a new built-in middleware between TrustProxies and TrimStrings, your BlockBannedIps stays exactly where you placed it — after TrustProxies.

Edge cases to keep in mind

Silent no-op when target is missing

If you reference a middleware class that isn't in the stack (typo, removed in a future version, or you removed it yourself), nothing is inserted and no warning is emitted. This is by design — it prevents a missing target from breaking your application — but it means you should verify the final stack in tests or with php artisan middleware:show.

php artisan middleware:show
# or for a specific group
php artisan middleware:show web

Removing the target doesn't remove your middleware

If you later call $middleware->remove(TrustProxies::class), your BlockBannedIps middleware remains in the stack at its current position. The insertion creates a permanent entry; it's not a dynamic "anchor" that moves or disappears with the target.

Order of operations in bootstrap/app.php

Middleware configuration is applied in the order you write it. If you both insertAfter and remove the same target, the last call wins. Keep related calls grouped and commented for clarity.

->withMiddleware(function (Middleware $middleware) {
    // IP handling — must run after TrustProxies
    $middleware->insertAfter(TrustProxies::class, BlockBannedIps::class);
    
    // Input sanitization — must run before TrimStrings
    $middleware->insertBefore(TrimStrings::class, SanitizeInput::class);
    
    // Session-based locale — web group only
    $middleware->insertAfterInGroup('web', StartSession::class, SetLocaleFromSession::class);
})

When to use this vs. the old approach

Situation Recommended approach
Middleware belongs at the very start or end prepend() / append() — simpler, intent is clear
Middleware must run relative to a specific built-in class insertBefore() / insertAfter() — precise, upgrade-safe
You need to replace a built-in middleware entirely replace() / replaceInGroup()
You're building a package that adds middleware Document the target class; let the consuming app decide position with insertBefore/insertAfter

A note on testing

Since the insertion is configuration-only, you can verify it in a feature test by checking the resolved middleware stack:

use Illuminate\Http\Middleware\TrustProxies;
use App\Http\Middleware\BlockBannedIps;

test('BlockBannedIps runs after TrustProxies', function () {
    $stack = app(\Illuminate\Contracts\Http\Kernel::class)->getMiddleware();
    
    $trustProxiesIndex = array_search(TrustProxies::class, $stack);
    $blockBannedIndex = array_search(BlockBannedIps::class, $stack);
    
    expect($blockBannedIndex)->toBeGreaterThan($trustProxiesIndex);
});

For group-specific middleware, inspect $kernel->getMiddlewareGroup('web') instead.

Takeaway

The new insertBefore, insertAfter, insertBeforeInGroup, and insertAfterInGroup methods give you surgical control over middleware ordering without the brittleness of maintaining a full stack copy. They're a small API addition that eliminates a whole class of upgrade headaches — exactly the kind of incremental improvement that makes Laravel pleasant to maintain over years.

If you've ever copied the default middleware array into bootstrap/app.php just to squeeze one class between TrustProxies and TrimStrings, you can now delete that code and use the new API instead.

Sources