Middleware

HTTP middleware is an useful mechanism in web apps. It is responsible for filtering and altering incoming requests.

Basic Middleware

To create a middleware, you can leverage the CLI:

      

terminal

entropy make middleware auth

An example midleware class for authentication may look like this:

      

src/auth/auth.middleware.ts

import { HttpRequest, Middleware } from '@entropy/http'; export class AuthMiddleware implements Middleware { public async handle(request: HttpRequest): Promise { if (!await request.session.get('authenticated')) { // Redirect user... } } }

Middleware is called by the handle method before a controller action.

Using Middleware

In order to use a middleware, you should register it for a route using the middleware route option:

      

src/users/user.controller.ts

import { HttpRequest } from '@entropy/http'; import { Controller, Route } from '@entropy/router'; export class UserController extends Controller { @Route.Get('/users/:id/dashboard', { middleware: [AuthMiddleware], }) public dashboard([id]: [string], request: HttpRequest) { // This route is visible only for authenticated users } }
Session HTTP Client