Guard
Guards decide whether a request can continue. They run before middleware and handlers.
Guards must implement the Guard<TRequest> interface:
interface Guard<TRequest = any> {
activate(request: TRequest): Promise<boolean> | boolean;
}
activate
Determines whether a request can continue. If activate returns true, the request proceeds to the next guard or handler. If it returns false, the request is short-circuited with a 403 Forbidden by default. A guard can also throw an ErrorHttpResponse (for example, ForbiddenHttpResponse), which will be sent as-is.
Adapter-specific examples
Each adapter has its own request type. Below is a minimal “allow” guard for each adapter.
- Express 4
- Express 5
- Fastify
- Hono
- uWebSockets.js
export class Express4AllowGuard implements ExpressGuard {
public async activate(_request: Request): Promise<boolean> {
return true;
}
}
export class ExpressAllowGuard implements ExpressGuard {
public async activate(_request: Request): Promise<boolean> {
return true;
}
}
export class FastifyAllowGuard implements FastifyGuard {
public async activate(_request: FastifyRequest): Promise<boolean> {
return true;
}
}
export class HonoAllowGuard implements HonoGuard {
public async activate(_request: HonoRequest): Promise<boolean> {
return true;
}
}
export class UwebsocketsAllowGuard implements UwebSocketsGuard {
public async activate(_request: HttpRequest): Promise<boolean> {
return true;
}
}
Deny with a custom error response
Below are minimal “deny” guards that throw a ForbiddenHttpResponse directly.
- Express 4
- Express 5
- Fastify
- Hono
- uWebSockets.js
export class Express4DenyGuard implements ExpressGuard {
public activate(_request: Request): boolean {
throw new ForbiddenHttpResponse(
{ message: 'Missing or invalid credentials' },
'Missing or invalid credentials',
);
}
}
export class ExpressDenyGuard implements ExpressGuard {
public activate(_request: Request): boolean {
throw new ForbiddenHttpResponse(
{ message: 'Missing or invalid credentials' },
'Missing or invalid credentials',
);
}
}
export class FastifyDenyGuard implements FastifyGuard {
public activate(_request: FastifyRequest): boolean {
throw new ForbiddenHttpResponse(
{ message: 'Missing or invalid credentials' },
'Missing or invalid credentials',
);
}
}
export class HonoDenyGuard implements HonoGuard {
public activate(_request: HonoRequest): boolean {
throw new ForbiddenHttpResponse(
{ message: 'Missing or invalid credentials' },
'Missing or invalid credentials',
);
}
}
export class UwebsocketsDenyGuard implements UwebSocketsGuard {
public activate(_request: HttpRequest): boolean {
throw new ForbiddenHttpResponse(
{ message: 'Missing or invalid credentials' },
'Missing or invalid credentials',
);
}
}
Attaching guards
Use the UseGuard decorator at the controller level (applies to all routes) or at the method level (applies to one route).
Global guards can be registered using the InversifyHttpAdapter.