Skip to content

Documenting the @Public() Decorator

This document describes the purpose and usage of the @Public() decorator in a NestJS application.

Purpose:

  • Marks specific routes or controllers as publicly accessible without requiring user authentication or authorization.
  • Useful for open endpoints that don't require authentication, like login, registration, or API documentation.

Key Elements:

  • IS_PUBLIC_KEY Constant: Defines a unique key used to store the metadata set by the decorator.
  • Public Function:
    • Applies the SetMetadata function from @nestjs/common to associate the IS_PUBLIC_KEY with the value true.
    • Can be used directly on route handlers or at the controller level to mark all methods within the controller as public.

Usage:

typescript
import { Controller, Get, Public } from '@nestjs/common';

@Controller('auth')
export class AuthController {
  @Get('login')
  @Public()
  public login() {
    // ... Login logic
  }
}

In this example, the login method within the AuthController is marked as public using the @Public() decorator. This means that users won't need to be authenticated to access this endpoint.

Benefits:

  • Simplifies route definitions for publicly accessible endpoints.
  • Improves code clarity and organization by explicitly marking public routes.
  • Helps maintain a separate layer for public and protected resources.

Additional Notes:

  • The behavior of this decorator might depend on how authentication/authorization is implemented in your application.
  • Remember to secure other non-public routes with appropriate authentication and authorization mechanisms.
  • Always carefully consider the security implications of making routes public, as it bypasses authentication checks.

Use Cases:

  • Open registration endpoints
  • Login functionalities
  • Public API documentation access
  • Unauthenticated user data retrieval (if applicable)
  • Publicly available resources or content

This document provides a general understanding of the Public decorator in NestJS. Remember to adapt the details and use cases to your specific application and security requirements.

File Name: shared/decorator.ts