Verified SOP & TutorialAudited Score 98/100

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.

Target Runtimes:codexclaude-codecursorwindsurf
5 min read • Updated for 2026

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

Codex Desktop, Claude Code CLI, Cursor IDE, or Windsurf installed
Node.js 20+ with npm, pnpm, or yarn initialized in the project workspace
@nestjs/core, @nestjs/common, @nestjs/passport, passport, and @nestjs/jwt installed in workspace

Verified Search Intents & Long-Tail Queries Solved

SEO Audit Score: 98/100

This operational tutorial is engineered to provide deterministic solutions for these developer search queries:

#install nestjs-guards-jwt-passport in cursor ide#claude code nestjs-guards-jwt-passport rules#codex desktop nestjs-guards-jwt-passport setup tutorial#how to fix nestjs-guards-jwt-passport agent execution error#deterministic nestjs passport jwt agent SOP#nestjs-guards-jwt-passport sandbox permissions and security score#nestjs-guards-jwt-passport prompt examples and triggers#implement roles guard and refresh token rotation nestjs agent

Step-by-Step Execution Playbook

1

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.

Terminal Command
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
.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
---
Production Pro-Tip

Keep the SKILL.md scoped only to auth architecture rules; avoid inlining multi-megabyte package-lock JSON files into the agent's context window.

Sandbox Gotcha

Ensure fs_write permissions are scoped to 'workspace' so the agent cannot inadvertently overwrite system environment files or configuration outside the repository root.

2

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.

Terminal Command
npm install @nestjs/passport passport passport-jwt @nestjs/jwt && npm install -D @types/passport-jwt
src/auth/strategies/jwt.strategy.ts
import { 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 };
  }
}
Production Pro-Tip

Use ConfigService.getOrThrow() inside JwtStrategy to fail fast during module bootstrap if secrets are missing.

Sandbox Gotcha

Never commit plaintext JWT secrets or private keys directly to agent prompt instructions or version control.

3

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.

src/auth/guards/roles.guard.ts
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));
  }
}
Production Pro-Tip

Use Reflector.getAllAndOverride to allow endpoint-level role definitions to override controller-level role defaults seamlessly.

Sandbox Gotcha

Ensure JwtAuthGuard runs before RolesGuard; otherwise, request.user will be undefined when the role check executes.

4

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.

Terminal Command
npm run build && npm run test:e2e
src/auth/auth.module.ts
import { 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 {}
Production Pro-Tip

Run a targeted unit test on the RolesGuard execution context to verify authorization matrices without needing a running database.

Sandbox Gotcha

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

Tested Trigger Prompt (Feed directly into Codex, Claude, or Cursor):

“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.”

Deterministic Agent Verification Pipeline:
Detected trigger 'create nestjs authguard' and matched skill 'nestjs-guards-jwt-passport'.
Created src/auth/decorators/roles.decorator.ts with SetMetadata and custom Roles decorator.
Implemented src/auth/guards/jwt-auth.guard.ts extending AuthGuard('jwt').
Implemented src/auth/guards/roles.guard.ts with Reflector checking against request.user.
Constructed src/analytics/analytics.controller.ts decorated with @UseGuards(JwtAuthGuard, RolesGuard) and @Roles('admin').
Executed 'npm run build' to confirm zero TypeScript compilation errors.

Runtime Troubleshooting & Failure Modes

Error: Error: Nest can't resolve dependencies of the JwtStrategy (?). Please make sure that the argument ConfigService at index [0] is available in the AuthModule context.

Root Cause: ConfigModule was not imported into AuthModule, or ConfigModule was not registered globally with isGlobal: true in AppModule.

Resolution Command / Fix:
Add 'ConfigModule.forRoot({ isGlobal: true })' to AppModule imports or explicitly import 'ConfigModule' into AuthModule.
Error: TypeError: Cannot read properties of undefined (reading 'roles')

Root Cause: RolesGuard executed prior to JwtAuthGuard or without authentication, meaning request.user was not populated by Passport before the role evaluation.

Resolution Command / Fix:
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.

Get 1-Click Install Spec