Demo

Middleware

Apply auth, permission, and audit middleware on controllers — register plugin-wide filters with @Module globalFilter / globalExceptionsFilter — or build your own with @Middleware.

Usage

Decorate a controller class (all routes) or a single method. Stack middlewares in the order they should run — auth before permission is typical for admin APIs. For every request across the app, use globalFilter on the root @Module instead.

TSXusage
1import { 2 AuditLogMiddleware, 3 AuthenticatedUserOnly, 4 CheckAPIPermission, 5 Controller, 6 Get, 7 ResponseDto, 8} from "@quan-erp/shared-backend-core"; 9 10@Controller("/admin-dashboard") 11export class AdminDashboardController { 12 @Get("/stats") 13 @AuthenticatedUserOnly() 14 @CheckAPIPermission() 15 @AuditLogMiddleware((req) => `View stats`) 16 async getStats() { 17 return ResponseDto.ok(data); 18 } 19}

Builtin middleware

  • @AuthenticatedUserOnly() — reject unauthenticated callers with 401; use on any logged-in endpoint
  • @CheckAPIPermission() — check the user’s role against allowed APIs for the current method + URL; pair with @AuthenticatedUserOnly on admin routes
  • @AuditLogMiddleware(action) — static string or (req) => string for audit trail entries on sensitive actions
TSXaudit
1import { 2 AuditLogMiddleware, 3 Controller, 4 Get, 5 Put, 6} from "@quan-erp/shared-backend-core"; 7 8@Controller("/branch") 9export class BranchController { 10 @AuditLogMiddleware("View all branches") 11 @Get("/") 12 async getAll() { /* … */ } 13 14 @AuditLogMiddleware((req) => `Update branch ${req.params.id}`) 15 @Put("/:id") 16 async update() { /* … */ } 17}

Global middleware (module)

Register filters on the root @Module so they run for every request (not just one controller). Use globalFilter for request middleware and globalExceptionsFilter for error handlers. Core unregisters them when the plugin is uninstalled.

  • globalFilter: { position, handler }[] — app-wide request middleware
  • globalExceptionsFilter: handler[] — app-wide exception middleware (IExceptionMiddleware)
  • MiddlewarePosition.BEFORE_ROOT_ROUTE — run before plugin root routes (typical for auth / resolve-user / logging)
  • MiddlewarePosition.AFTER_ROOT_ROUTE — run after the root stack
  • Handler — Express RequestHandler or a class implementing IExpressMiddleware / IExceptionMiddleware
  • Required on every class middleware: @MiddlewareMetadata({ plugin: metadata.name })
TSXglobalFilter on @Module
1import { 2 MiddlewareMetadata, 3 MiddlewarePosition, 4 Module, 5} from "@quan-erp/shared-backend-core"; 6import type { 7 IExceptionMiddleware, 8 IExpressMiddleware, 9} from "@quan-erp/shared-backend-core"; 10import type { NextFunction, Request, Response } from "express"; 11import metadata from "../../module.metadata.json" with { type: "json" }; 12import { MyController } from "./my.controller.js"; 13import { MyService } from "./my.service.js"; 14 15@MiddlewareMetadata({ plugin: metadata.name }) 16export class RequestIdMiddleware implements IExpressMiddleware { 17 handler(req: Request, res: Response, next: NextFunction) { 18 res.setHeader("x-request-plugin", metadata.name); 19 return next(); 20 } 21} 22 23@MiddlewareMetadata({ plugin: metadata.name }) 24export class PluginErrorFilter implements IExceptionMiddleware { 25 handler(error: Error, req: Request, res: Response, next: NextFunction) { 26 if (res.headersSent) return next(error); 27 res.status(500).json({ message: error.message }); 28 } 29} 30 31@Module({ 32 name: metadata.name, 33 providers: [MyService], 34 controllers: [MyController], 35 entities: [], 36 globalFilter: [ 37 { 38 position: MiddlewarePosition.BEFORE_ROOT_ROUTE, 39 handler: RequestIdMiddleware, 40 }, 41 ], 42 globalExceptionsFilter: [PluginErrorFilter], 43}) 44export class MyPluginModule {}

Creating custom middleware

Wrap logic with Middleware(...) as a decorator for controller/method scope, or implement IExpressMiddleware / IExceptionMiddleware for DI-aware handlers (also used in globalFilter). Every class middleware MUST declare @MiddlewareMetadata({ plugin: metadata.name }) so the core resolves it in the correct plugin DI scope. Apply route middleware with @MyDecorator() or @Middleware(MyClass).

  • Required: @MiddlewareMetadata({ plugin: metadata.name }) on every class that implements IExpressMiddleware / IExceptionMiddleware
  • Decorator-based — return Middleware(async (req, res, next) => { … }) from a factory (no MiddlewareMetadata — function handlers)
  • Class-based (IExpressMiddleware) — handler(req, res, next); @Inject works without @Service()
  • Exception middleware (IExceptionMiddleware) — handler(error, req, res, next)
  • Keep middleware focused; put business rules in services when possible
TSXdecorator middleware
1import { 2 HttpStatus, 3 Middleware, 4 ResponseDto, 5} from "@quan-erp/shared-backend-core"; 6 7export function MyCustomAuth(): MethodDecorator & ClassDecorator { 8 return Middleware(async (req, res, next) => { 9 if (req.headers["x-custom-header"] === "secret-value") return next(); 10 return res 11 .status(HttpStatus.UNAUTHORIZED) 12 .json(ResponseDto.error("Unauthorized", HttpStatus.UNAUTHORIZED)); 13 }); 14}
TSXclass middleware
1import type { NextFunction, Request, Response } from "express"; 2import { 3 Controller, 4 Inject, 5 Middleware, 6 MiddlewareMetadata, 7} from "@quan-erp/shared-backend-core"; 8import type { IExpressMiddleware } from "@quan-erp/shared-backend-core"; 9import metadata from "../../module.metadata.json" with { type: "json" }; 10import { MyService } from "./my.service.js"; 11 12@MiddlewareMetadata({ plugin: metadata.name }) 13export class MyComplexMiddleware implements IExpressMiddleware { 14 @Inject(MyService) 15 private myService: MyService; 16 17 async handler(req: Request, res: Response, next: NextFunction) { 18 if (await this.myService.validate(req.body)) return next(); 19 res.status(400).send("Invalid request"); 20 } 21} 22 23@Middleware(MyComplexMiddleware) 24@Controller("/complex") 25export class ComplexController {}