The Complete Production SOP: How to Deploy and Run NestJS Authentication Guards & Passport JWT Strategies in Autonomous AI Agents
Production SOP to install and run NestJS Authentication Guards & Passport JWT Strategies in Codex, Claude Code, and Cursor. Includes verified code and prompts.
Technical Overview & Architectural Context
Autonomous coding agents frequently misconfigure enterprise authentication in NestJS applications. Common hallucinations include mixing Express middleware with NestJS ExecutionContext, forgetting to provide Reflector to RolesGuard, failing to register JwtStrategy in the AuthModule providers array, or insecurely storing unhashed refresh tokens in the database. When an agent attempts to implement role-based access control (RBAC), it often writes brittle controller-level checks instead of declarative metadata decorators. The 'nestjs-guards-jwt-passport' skill eliminates non-deterministic auth implementations by enforcing strict architectural guardrails. It mandates standard PassportStrategy extensions, type-safe payload extraction via custom parameter decorators, and centralized token verification flows. Autonomous agents running in Claude Code, Codex Desktop, Windsurf, or Cursor execute against concrete file structures, strict workspace permissions, and mandatory build-verification loops.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules into the agent runtime path.
Autonomous runtimes such as Claude Code and Codex look for skills in dedicated user or workspace directories (e.g., .agents/skills or .claude/skills). Mounting the SKILL.md specification instructs the runtime on supported triggers, allowed filesystem boundaries, and deterministic implementation steps for Passport strategies and NestJS guards.
mkdir -p .agents/skills/nestjs-guards-jwt-passport && curl -fsSL https://askills.dev/api/skills/nestjs-guards-jwt-passport/raw -o .agents/skills/nestjs-guards-jwt-passport/SKILL.md---
name: "nestjs-guards-jwt-passport"
description: "Secure API endpoints with Passport JWT strategies, refresh tokens, and Role-Based Guards."
metadata:
author: "NestJS"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "create nestjs authguard"
- "passport-jwt strategy nestjs"
- "roles guard nestjs"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---Keep the SKILL.md scoped only to auth architecture rules; avoid inlining multi-megabyte package-lock JSON files into the agent's context window.
Ensure fs_write permissions are scoped to 'workspace' so the agent cannot inadvertently overwrite system environment files or configuration outside the repository root.
Dependency Installation & Secret Configuration
Install Passport and JWT runtime packages and configure environment variables safely without secret leakage.
Passport requires underlying strategy drivers (@types/passport-jwt, passport-jwt). Configure the JWT secrets via NestJS ConfigService and .env files rather than hardcoding values into the prompt or strategy class.
npm install @nestjs/passport passport passport-jwt @nestjs/jwt && npm install -D @types/passport-jwtimport { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
export interface JwtPayload {
sub: string;
email: string;
roles: string[];
}
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.getOrThrow<string>('JWT_SECRET'),
});
}
async validate(payload: JwtPayload) {
if (!payload.sub) {
throw new UnauthorizedException('Invalid token claims');
}
return { userId: payload.sub, email: payload.email, roles: payload.roles };
}
}Use ConfigService.getOrThrow() inside JwtStrategy to fail fast during module bootstrap if secrets are missing.
Never commit plaintext JWT secrets or private keys directly to agent prompt instructions or version control.
Intent Matching & Trigger Invocation
Trigger the agent to generate declarative Role Guards and custom Decorators using precise keyword triggers.
Provide high-intent natural language instructions that activate the skill frontmatter triggers: 'create nestjs authguard' or 'roles guard nestjs'. The agent will generate the reflector-based guard and metadata decorators according to SOP rules.
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from '../decorators/roles.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles || requiredRoles.length === 0) {
return true;
}
const { user } = context.switchToHttp().getRequest();
return requiredRoles.some((role) => user?.roles?.includes(role));
}
}Use Reflector.getAllAndOverride to allow endpoint-level role definitions to override controller-level role defaults seamlessly.
Ensure JwtAuthGuard runs before RolesGuard; otherwise, request.user will be undefined when the role check executes.
Verification, Linting & Output Quality Gate
Execute automated self-healing checks and type validation before accepting agent deliverables.
Require the autonomous agent to verify module bindings in AuthModule and run TypeScript compilation checks. If JwtStrategy is missing from providers or exports, NestJS runtime dependency injection fails with UnknownElementException.
npm run build && npm run test:e2eimport { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtStrategy } from './strategies/jwt.strategy';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { RolesGuard } from './guards/roles.guard';
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
secret: config.getOrThrow<string>('JWT_SECRET'),
signOptions: { expiresIn: '15m' },
}),
}),
],
providers: [JwtStrategy, JwtAuthGuard, RolesGuard],
exports: [PassportModule, JwtModule, JwtAuthGuard, RolesGuard],
})
export class AuthModule {}Run a targeted unit test on the RolesGuard execution context to verify authorization matrices without needing a running database.
If PassportModule is not exported from AuthModule, consuming modules attempting to apply AuthGuard('jwt') will trigger circular dependency or DI injection errors.
Real-World Scenario: Implement RBAC Protected Admin Endpoints with JWT Authentication
“Using the nestjs-guards-jwt-passport skill: create nestjs authguard and roles guard nestjs for an analytics controller. Protect the /admin/metrics route so that only users with the 'admin' role can access it, extracting the JWT bearer token from the authorization header.”
Runtime Troubleshooting & Failure Modes
Root Cause: ConfigModule was not imported into AuthModule, or ConfigModule was not registered globally with isGlobal: true in AppModule.
Add 'ConfigModule.forRoot({ isGlobal: true })' to AppModule imports or explicitly import 'ConfigModule' into AuthModule.Root Cause: RolesGuard executed prior to JwtAuthGuard or without authentication, meaning request.user was not populated by Passport before the role evaluation.
Ensure controller or handler applies guards in sequential order: @UseGuards(JwtAuthGuard, RolesGuard).Frequently Asked Questions (NestJS Authentication Guards & Passport JWT Strategies SOP)
Q:Can I use NestJS Authentication Guards & Passport JWT Strategies across Codex, Claude Code, and Cursor simultaneously?
Yes. The SKILL.md specification is runtime-agnostic. Runtimes including OpenAI Codex, Claude Code CLI, Cursor, and Windsurf parse the frontmatter triggers and SOP rules without modification.
Q:How does NestJS Authentication Guards & Passport JWT Strategies prevent context window overflow during long agent sessions?
The skill provides compact procedural constraints and explicit class interfaces. Rather than loading whole repositories or repetitive NestJS documentation into agent context, it defines single-responsibility boundaries for strategies and guards.
Q:Does this skill require escalated root or container permissions?
No. It is audited with a security score of 98/100. It requires read access and workspace-scoped file write access, with shell execution and outbound network access disabled by default.
Ready to equip your autonomous agent with NestJS Authentication Guards & Passport JWT Strategies?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.