A reusable NestJS Auth guard for validating JWT tokens locally or trusting API Gateway headers in production. This guard automatically switches behavior based on the `NODE_ENV` environment variable.
npm install nest-auth-guardA reusable NestJS Auth guard for validating JWT tokens locally or trusting API Gateway headers in production. This guard automatically switches behavior based on the NODE_ENV environment variable.
---
- โ
Auth JWT validation when running locally
- โ
API Gateway passthrough validation in production (via trusted headers)
- โ
Works with Bearer tokens
- โ
Lightweight and configurable
- โ
Built for microservice environments
---
``bash`
npm install nest-auth-guard
`bash`
npm install @nestjs/common @nestjs/core @nestjs/passport passport passport-jwt ioredis
---
| Key | Example Value | Required | Description |
| ---------------- | ----------------------- | -------- | ------------------------------------- | --- |
| NODE_ENV | local or production | โ
| Used to switch between local and prod | |REDIS_HOST
| | localhost | โ
| Redis host (defaults to localhost) |REDIS_PORT
| | 6379 | โ
| Redis port (defaults to 6379) |REDIS_PASSWORD
| | your-password | โ | Redis password (optional) |REDIS_DB
| | 0 | โ
| Redis database index (defaults to 0) |REDIS_USERNAME
| | your-username | โ | Redis username (optional) |
Add these in your .env file:
`env
NODE_ENV=local
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=your-password # Optional
REDIS_DB=0 # Optional: database index
REDIS_USERNAME=your-username # Optional
`
> ๐ In production, you can set NODE_ENV=production and pass user info via x-user header.
---
In app.module.ts of your NestJS service:
`ts
import { ConfigModule } from "@nestjs/config";
@Module({
imports: [ConfigModule.forRoot({ isGlobal: true })],
})
export class AppModule {}
`
---
`ts
import { Controller, Get, Req, UseGuards } from "@nestjs/common";
import { AuthGuard } from "nest-auth0-guard";
@Controller("profile")
@UseGuards(AuthGuard)
export class ProfileController {
@Get()
getProfile(@Req() req) {
return req.user; // decoded token or forwarded user info
}
}
`
---
| NODE_ENV | Behavior |local
| ------------ | ------------------------------------------ |
| | Validates JWT from Authorization: Bearer |production
| | Reads user from x-user header |
The guard automatically fetches additional user data from Redis using the user.userId field as the key. If Redis data is found, it merges with the authenticated user object. The Redis key format is user:{user.userId}.
Example Redis data structure:
`json``
{
"user:68fb768c7f86363f4140899c": {
"preferences": { "theme": "dark" },
"profile": { "avatar": "https://example.com/avatar.jpg" },
"settings": { "notifications": true }
}
}