According to the docs, guards are supposed to run before they approach any request mapping. I have a basic guard that prints the current method:
import { Injectable, ExecutionContext, CanActivate } from '@nestjs/common';
@Injectable()
export class HttpMethodGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
console.log(request.raw.method)
return true;
}
}
In my main.ts file, I'm using it as a globalGuard:
app.useGlobalGuards(new HttpMethodGuard());
I was expecting that regardless of request to a given endpoint, that the guard would run. The reason being, I'd like to log security events in the case that somebody is sniffing. However, in my console, I do not see any console logs for route mappings that don't exist.
Is this expected? Is there any way I can implement something that is actually before everything?
Guards will run for all routes blind to the application via a controller. If a route does but exist, there is no guard for it. You could implement something similar with a global middleware for Express (or fastify as it looks to be the case here)
Most helpful comment
Guards will run for all routes blind to the application via a controller. If a route does but exist, there is no guard for it. You could implement something similar with a global middleware for Express (or fastify as it looks to be the case here)