Nest: Upon what condition do guards run?

Created on 15 Jul 2020  路  1Comment  路  Source: nestjs/nest

Question

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?

needs triage question 馃檶

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)

>All comments

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)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rlesniak picture rlesniak  路  3Comments

tronginc picture tronginc  路  3Comments

janckerchen picture janckerchen  路  3Comments

cojack picture cojack  路  3Comments

cdiaz picture cdiaz  路  3Comments