DEV Community

Discussion on: Exclude a route from Nest.js AuthGaurd (make any route publicly available)

Collapse
 
fsassiv profile image
FLAVIO SANTOS DE ANDRADE • Edited

I think a Custom Class decorator would be the solution for this.

1. Define the Decorator
First, create a new file for your custom decorator. Let's call it custom-class.decorator.ts.

typescript
import { SetMetadata } from '@nestjs/common';

export const CustomClass = (value: string): ClassDecorator => {
  return SetMetadata('customClassKey', value);
};
Here, SetMetadata is used to attach metadata to the class.

2. Apply the Custom Decorator
Apply this decorator to any class where you want to use it.

typescript
import { CustomClass } from './custom-class.decorator';

@CustomClass('myCustomValue')
export class ExampleService {
  // Your class logic here
}
3. Access the Metadata
To access this metadata, use the Reflector service in a guard, interceptor, or another provider.

typescript
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

@Injectable()
export class CustomGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const customValue = this.reflector.get<string>(
      'customClassKey',
      context.getClass(),
    );
    if (!customValue) {
      return true;
    }

    // Add your custom logic here
    console.log(`Custom value from decorator: ${customValue}`);
    return true;
  }
}
4. Register the Guard
Finally, apply the guard either globally, at the module level, or at the route level.

typescript
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { ExampleService } from './example.service';
import { CustomGuard } from './custom.guard';

@Module({
  providers: [
    ExampleService,
    {
      provide: APP_GUARD,
      useClass: CustomGuard,
    },
  ],
})
export class AppModule
Enter fullscreen mode Exit fullscreen mode