Skip to main content

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.

export class ExpressAllowGuard implements ExpressGuard {
public async activate(_request: Request): Promise<boolean> {
return true;
}
}

Deny with a custom error response​

Below are minimal “deny” guards that throw a ForbiddenHttpResponse directly.

export class ExpressDenyGuard implements ExpressGuard {
public activate(_request: Request): 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.