LaraflareDocsPackages13.x

Docs / The Basics / Middleware

Middleware

Introduction

Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application. For example, Laraflare includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to your application's login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

Additional middleware can be written to perform a variety of tasks besides authentication. For example, a logging middleware might log all incoming requests to your application. A variety of middleware are included in Laraflare, including middleware for authentication and CSRF protection; however, all user-defined middleware are typically located in your application's app/Http/Middleware directory.

Defining Middleware

To create a new middleware, use the make:middleware Artisan command:

npx artisan make:middleware EnsureTokenIsValid

This command will place a new EnsureTokenIsValid class within your app/Http/Middleware directory. In this middleware, we will only allow access to the route if the supplied token input matches a specified value. Otherwise, we will redirect the users back to the /home URI:

import { redirect, type Request } from '@laraflare/framework';

export class EnsureTokenIsValid {
  /**
   * Handle an incoming request.
   */
  handle(request: Request, next: (request: Request) => Promise<Response>): Promise<Response> | Response {
    if (request.input('token') !== 'my-secret-token') {
      return redirect('/home');
    }

    return next(request);
  }
}

As you can see, if the given token does not match our secret token, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. To pass the request deeper into the application (allowing the middleware to "pass"), you should call the next callback with the request.

It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely.

Note

All middleware are resolved via the service container, so you may type-hint any dependencies you need within a middleware's constructor.

Note

On Workers, next answers a promise, so a middleware that looks at the response awaits it (or returns the promise). The response is the Fetch API's Response.

Middleware and Responses

Of course, a middleware can perform tasks before or after passing the request deeper into the application. For example, the following middleware would perform some task before the request is handled by the application:

import type { Request } from '@laraflare/framework';

export class BeforeMiddleware {
  handle(request: Request, next: (request: Request) => Promise<Response>): Promise<Response> {
    // Perform action

    return next(request);
  }
}

However, this middleware would perform its task after the request is handled by the application:

import type { Request } from '@laraflare/framework';

export class AfterMiddleware {
  async handle(request: Request, next: (request: Request) => Promise<Response>): Promise<Response> {
    const response = await next(request);

    // Perform action

    return response;
  }
}

Registering Middleware

Global Middleware

If you want a middleware to run during every HTTP request to your application, you may append it to the global middleware stack in your application's bootstrap/app.ts file:

import { EnsureTokenIsValid } from '../app/Http/Middleware/EnsureTokenIsValid';

.withMiddleware((middleware) => {
  middleware.append(EnsureTokenIsValid);
})

The middleware object provided to the withMiddleware callback is an instance of Laraflare's Middleware class and is responsible for managing the middleware assigned to your application's routes. The append method adds the middleware to the end of the list of global middleware. If you would like to add a middleware to the beginning of the list, you should use the prepend method.

If a middleware needs to run at a specific point in Laraflare's default global middleware stack, you may use the insertBefore and insertAfter methods. Both methods accept the middleware already in the stack that you want to position against, followed by the middleware you want to insert:

import { TrimStrings, TrustProxies } from '@laraflare/framework';
import { SanitizeInput } from '../app/Http/Middleware/SanitizeInput';
import { StripCrossOriginReferer } from '../app/Http/Middleware/StripCrossOriginReferer';

.withMiddleware((middleware) => {
  middleware.insertAfter(TrustProxies, StripCrossOriginReferer);

  middleware.insertBefore(TrimStrings, SanitizeInput);
})

You may also pass an array of middleware as the second argument to either method.

Warning

If the middleware you are positioning against is not part of the global middleware stack, nothing will be inserted.

Manually Managing Laraflare's Default Global Middleware

If you would like to manage Laraflare's global middleware stack manually, you may provide Laraflare's default stack of global middleware to the use method. Then, you may adjust the default middleware stack as necessary:

import {
  ConvertEmptyStringsToNull,
  HandleCors,
  PreventRequestsDuringMaintenance,
  TrimStrings,
  TrustProxies,
  ValidatePathEncoding,
  ValidatePostSize,
} from '@laraflare/framework';

.withMiddleware((middleware) => {
  middleware.use([
    ValidatePathEncoding,
    // TrustHosts,
    TrustProxies,
    HandleCors,
    PreventRequestsDuringMaintenance,
    ValidatePostSize,
    TrimStrings,
    ConvertEmptyStringsToNull,
  ]);
})

Assigning Middleware to Routes

If you would like to assign middleware to specific routes, you may invoke the middleware method when defining the route:

import { Route } from '@laraflare/framework';
import { EnsureTokenIsValid } from '../app/Http/Middleware/EnsureTokenIsValid';

Route.get('/profile', () => {
  // ...
}).middleware(EnsureTokenIsValid);

You may assign multiple middleware to the route by passing an array of middleware names to the middleware method:

Route.get('/', () => {
  // ...
}).middleware([First, Second]);

Excluding Middleware

When assigning middleware to a group of routes, you may occasionally need to prevent the middleware from being applied to an individual route within the group. You may accomplish this using the withoutMiddleware method:

import { Route } from '@laraflare/framework';
import { EnsureTokenIsValid } from '../app/Http/Middleware/EnsureTokenIsValid';

Route.middleware([EnsureTokenIsValid]).group(() => {
  Route.get('/', () => {
    // ...
  });

  Route.get('/profile', () => {
    // ...
  }).withoutMiddleware([EnsureTokenIsValid]);
});

You may also exclude a given set of middleware from an entire group of route definitions:

import { Route } from '@laraflare/framework';
import { EnsureTokenIsValid } from '../app/Http/Middleware/EnsureTokenIsValid';

Route.withoutMiddleware([EnsureTokenIsValid]).group(() => {
  Route.get('/profile', () => {
    // ...
  });
});

The withoutMiddleware method can only remove route middleware and does not apply to global middleware.

Middleware Groups

Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. You may accomplish this using the appendToGroup method within your application's bootstrap/app.ts file:

import { First } from '../app/Http/Middleware/First';
import { Second } from '../app/Http/Middleware/Second';

.withMiddleware((middleware) => {
  middleware.appendToGroup('group-name', [
    First,
    Second,
  ]);

  middleware.prependToGroup('group-name', [
    First,
    Second,
  ]);
})

Middleware groups may be assigned to routes and controller actions using the same syntax as individual middleware:

Route.get('/', () => {
  // ...
}).middleware('group-name');

Route.middleware(['group-name']).group(() => {
  // ...
});

Laraflare's Default Middleware Groups

Laraflare includes predefined web and api middleware groups that contain common middleware you may want to apply to your web and API routes. Remember, Laraflare automatically applies these middleware groups to the corresponding routes/web.ts and routes/api.ts files:

The web Middleware Group
EncryptCookies
AddQueuedCookiesToResponse
StartSession
ValidateCsrfToken
SubstituteBindings
The api Middleware Group
SubstituteBindings

If you would like to append or prepend middleware to these groups, you may use the web and api methods within your application's bootstrap/app.ts file. The web and api methods are convenient alternatives to the appendToGroup method:

import { EnsureTokenIsValid } from '../app/Http/Middleware/EnsureTokenIsValid';
import { EnsureUserIsSubscribed } from '../app/Http/Middleware/EnsureUserIsSubscribed';

.withMiddleware((middleware) => {
  middleware.web({ append: [
    EnsureUserIsSubscribed,
  ] });

  middleware.api({ prepend: [
    EnsureTokenIsValid,
  ] });
})

You may even replace one of Laraflare's default middleware group entries with a custom middleware of your own:

import { StartSession } from '@laraflare/framework';
import { StartCustomSession } from '../app/Http/Middleware/StartCustomSession';

middleware.web({ replace: [
  [StartSession, StartCustomSession],
] });

Or, you may remove a middleware entirely:

middleware.web({ remove: [
  StartSession,
] });

If you need a middleware to run at a particular position within a group, you may use the insertBeforeInGroup and insertAfterInGroup methods:

import { StartSession } from '@laraflare/framework';
import { EnsureUserIsSubscribed } from '../app/Http/Middleware/EnsureUserIsSubscribed';

middleware.insertAfterInGroup('web', StartSession, EnsureUserIsSubscribed);

Manually Managing Laraflare's Default Middleware Groups

If you would like to manually manage all of the middleware within Laraflare's default web and api middleware groups, you may redefine the groups entirely. The example below will define the web and api middleware groups with their default middleware, allowing you to customize them as necessary:

import {
  AddQueuedCookiesToResponse,
  EncryptCookies,
  StartSession,
  SubstituteBindings,
  ValidateCsrfToken,
} from '@laraflare/framework';

.withMiddleware((middleware) => {
  middleware.group('web', [
    EncryptCookies,
    AddQueuedCookiesToResponse,
    StartSession,
    ValidateCsrfToken,
    SubstituteBindings,
    // 'auth.session',
  ]);

  middleware.group('api', [
    // 'throttle:api',
    SubstituteBindings,
  ]);
})

Note

By default, the web and api middleware groups are automatically applied to your application's corresponding routes/web.ts and routes/api.ts files.

Middleware Aliases

You may assign aliases to middleware in your application's bootstrap/app.ts file. Middleware aliases allow you to define a short alias for a given middleware class, which can be especially useful for middleware with long class names:

import { EnsureUserIsSubscribed } from '../app/Http/Middleware/EnsureUserIsSubscribed';

.withMiddleware((middleware) => {
  middleware.alias({
    subscribed: EnsureUserIsSubscribed,
  });
})

Once the middleware alias has been defined in your application's bootstrap/app.ts file, you may use the alias when assigning the middleware to routes:

Route.get('/profile', () => {
  // ...
}).middleware('subscribed');

Note

Calling alias replaces the aliases you set earlier in the same withMiddleware callback, so pass every alias in one call. Laraflare's own aliases below stay in place.

For convenience, some of Laraflare's built-in middleware are aliased by default. For example, the auth middleware is an alias for Laraflare's Authenticate middleware. Below is a list of the default middleware aliases:

Alias Middleware
auth Authenticate
auth.basic AuthenticateWithBasicAuth
auth.session AuthenticateSession
cache.headers SetCacheHeaders
can Authorize
durable-object RunInsideDurableObject
guest RedirectIfAuthenticated
password.confirm RequirePassword
precognitive HandlePrecognitiveRequests
signed ValidateSignature
throttle ThrottleRequests
verified EnsureEmailIsVerified

Sorting Middleware

Rarely, you may need your middleware to execute in a specific order but not have control over their order when they are assigned to the route. In these situations, you may specify your middleware priority using the priority method in your application's bootstrap/app.ts file:

import {
  AddQueuedCookiesToResponse,
  EncryptCookies,
  StartSession,
  SubstituteBindings,
  ValidateCsrfToken,
} from '@laraflare/framework';

.withMiddleware((middleware) => {
  middleware.priority([
    EncryptCookies,
    AddQueuedCookiesToResponse,
    StartSession,
    ValidateCsrfToken,
    SubstituteBindings,
  ]);
})

If you would like to add middleware to the existing priority list without replacing it, you may use the prependToPriorityList or appendToPriorityList methods. The prependToPriorityList method inserts the given middleware before another middleware, while the appendToPriorityList method inserts it after another middleware:

import { SubstituteBindings } from '@laraflare/framework';
import { EnsureTokenIsValid } from '../app/Http/Middleware/EnsureTokenIsValid';
import { EnsureUserIsSubscribed } from '../app/Http/Middleware/EnsureUserIsSubscribed';

.withMiddleware((middleware) => {
  middleware.prependToPriorityList(SubstituteBindings, EnsureTokenIsValid);

  middleware.appendToPriorityList(SubstituteBindings, EnsureUserIsSubscribed);
})

The first argument is the middleware to position against, and the second is the middleware to insert.

Middleware Parameters

Middleware can also receive additional parameters. For example, if your application needs to verify that the authenticated user has a given "role" before performing a given action, you could create an EnsureUserHasRole middleware that receives a role name as an additional argument.

Additional middleware parameters will be passed to the middleware after the next argument:

import { redirect, type Request } from '@laraflare/framework';

export class EnsureUserHasRole {
  /**
   * Handle an incoming request.
   */
  handle(request: Request, next: (request: Request) => Promise<Response>, role: string): Promise<Response> | Response {
    if (! request.user().hasRole(role)) {
      // Redirect...
    }

    return next(request);
  }
}

Middleware parameters may be specified when defining the route by separating the middleware's alias and parameters with a :. Give the middleware an alias first, such as role:

Route.put('/post/{id}', (id: string) => {
  // ...
}).middleware('role:editor');

Multiple parameters may be delimited by commas:

Route.put('/post/{id}', (id: string) => {
  // ...
}).middleware('role:editor,publisher');

Parameters reach handle as strings.

Terminable Middleware

Sometimes a middleware may need to do some work after the HTTP response has been sent to the browser. If you define a terminate method on your middleware, it will automatically be called after the response is sent to the browser:

import type { Request } from '@laraflare/framework';

export class TerminatingMiddleware {
  /**
   * Handle an incoming request.
   */
  handle(request: Request, next: (request: Request) => Promise<Response>): Promise<Response> {
    return next(request);
  }

  /**
   * Handle tasks after the response has been sent to the browser.
   */
  terminate(request: Request, response: Response): void {
    // ...
  }
}

The terminate method should receive both the request and the response. Once you have defined a terminable middleware, you should add it to the list of routes or global middleware in your application's bootstrap/app.ts file.

When calling the terminate method on your middleware, Laraflare will resolve a fresh instance of the middleware from the service container. If you would like to use the same middleware instance when the handle and terminate methods are called, register the middleware with the container using the container's singleton method. Typically this should be done in the register method of your AppServiceProvider:

import { ServiceProvider } from '@laraflare/framework';
import { TerminatingMiddleware } from '../Http/Middleware/TerminatingMiddleware';

export class AppServiceProvider extends ServiceProvider {
  /**
   * Register any application services.
   */
  override register(): void {
    this.app.singleton(TerminatingMiddleware);
  }
}
Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.