How Route Protection works with AuthGuard
masterThe library registers an AuthGuard globally by default. This means all routes in your application are protected unless you explicitly opt-out using decorators.
- REST & GraphQL: The global guard applies to both controllers and resolvers. Use
@AllowAnonymous()to make a route public or@OptionalAuth()to make authentication optional. - WebSockets: The global guard also applies to WebSocket connections. To protect a Gateway or specific messages, you must apply the
AuthGuardusing@UseGuards(AuthGuard)at the Gateway or Message level.
import { SubscribeMessage, WebSocketGateway } from "@nestjs/websockets";
import { UseGuards } from "@nestjs/common";
import { AuthGuard } from '@thallesp/nestjs-better-auth';
@WebSocketGateway({
path: "/ws",
namespace: "test",
cors: {
origin: "*",
},
})
@UseGuards(AuthGuard)
export class TestGateway { /* ... */ }