Skip to Content
UsageProtecting Routes

Protecting Routes

AuthgearAuthGuard validates the incoming Authorization: Bearer <token> header. When the token is valid, the request proceeds and the verified claims are attached to the request; otherwise the guard throws an UnauthorizedException (HTTP 401).

There are two ways to apply it.

Global guard

Pass global: true to forRoot / forRootAsync. This registers the guard as a NestJS APP_GUARD, so every route is protected by default.

app.module.ts

With a global guard, opt specific routes out with @Public().

Per-route guard

If you do not register the guard globally, apply it to individual controllers or handlers with @UseGuards:

cats.controller.ts

You can also guard an entire controller by decorating the class:

@UseGuards(AuthgearAuthGuard) @Controller("cats") export class CatsController {}

Public routes

When the guard is global, mark routes that should skip authentication with @Public(). It works on a single handler or on a whole controller.

app.controller.ts

@Public() only has an effect when the guard runs. If you guard routes per-handler with @UseGuards, simply omit the guard from the routes you want to leave open instead of using @Public().

Next steps

Last updated on