Skip to content

Repository files navigation

npm version Node.js NestJS License

nestjs-auth-kit

CLI scaffolder that generates a complete authentication module inside an existing NestJS project.
No manual wiring required.

Installation · Usage · What it generates · Post-install · Local development


Installation

From the root of your NestJS project:

# No global install required (recommended)
pnpm dlx @dylantovar/nestjs-auth-kit init

# With npx
npx @dylantovar/nestjs-auth-kit init

# Global
pnpm add -g @dylantovar/nestjs-auth-kit && nestjs-auth-kit init

Requirements

  • Node.js ≥ 18
  • NestJS project with an existing src/app.module.ts
  • PostgreSQL or any TypeORM-compatible database

Interactive flow

The CLI asks up to 7 questions and adapts the output to your answers:

? Which ORM are you using?
  ❯ TypeORM
    Prisma (Coming soon)

? Which JWT strategy do you want to implement?
  ❯ Access + Refresh token rotation
    Access token only

? Add Role-Based Access Control (RBAC)?
  ❯ Yes

? Which roles will your system have?
  default: ADMIN, USER

? Add rate limiting to login endpoints?
  ❯ Yes

? Which storage backend for rate limiting?
  ❯ In-Memory
    Redis

? Generate a docker-compose.yml for DB (and Redis if applicable)?
  ❯ Yes

When finished, the CLI prints the exact dependency install command for your configuration and points to the README-AUTH.md generated in your project.


What it generates

your-nestjs-project/
├── .env.example                   # Environment variable reference
├── README-AUTH.md                 # Step-by-step integration guide
├── docker-compose.yml             # ← optional (PostgreSQL + Redis)
│
└── src/
    ├── config/
    │   ├── configuration.ts       # Typed env config
    │   ├── env.validation.ts      # Joi validation on boot
    │   └── database.config.ts     # TypeORM + DataSource for migrations
    │
    └── modules/
        └── auth/
            ├── auth.module.ts
            ├── auth.controller.ts
            ├── auth.service.ts
            ├── account.entity.ts
            ├── refresh-token.entity.ts        # ← Access + Refresh only
            ├── dto/
            │   ├── login.dto.ts
            │   ├── register.dto.ts
            │   └── refresh-token.dto.ts       # ← Access + Refresh only
            ├── enums/
            │   └── role.enum.ts               # ← RBAC only
            ├── guards/
            │   ├── jwt-auth.guard.ts
            │   └── roles.guard.ts             # ← RBAC only
            ├── decorators/
            │   ├── current-user.decorator.ts
            │   └── roles.decorator.ts         # ← RBAC only
            └── strategies/
                ├── jwt.strategy.ts
                └── jwt-refresh.strategy.ts    # ← Access + Refresh only

Endpoints

Method Path Auth Notes
POST /auth/register — Creates account
POST /auth/login — Rate limited if enabled
POST /auth/refresh Refresh token Access + Refresh only
POST /auth/logout JWT / Refresh Revokes token if applicable
POST /auth/me JWT Returns authenticated user payload

Features

Feature Description
Interactive CLI Dynamic prompts; output adapts to your choices
TypeORM + PostgreSQL Entities, DB config and DataSource for migrations (Prisma on roadmap)
Flexible JWT Access token only or Access + Refresh with rotation and DB revocation
RBAC Custom roles at setup, @Roles() decorator and exported RolesGuard
Rate limiting @nestjs/throttler on login — In-Memory or distributed Redis
Docker Compose PostgreSQL + Redis optional; does not overwrite an existing compose file
Typed config configuration.ts + Joi validation on startup
.env.example Auto-generated with variables based on your configuration
README-AUTH.md Integration guide with curl examples, Docker steps and RBAC example

Production-grade practices

The generated code is not a tutorial snippet:

  • bcrypt with saltRounds: 12
  • Refresh token rotation — every refresh revokes the previous token and issues a new one
  • DB revocation with revokedAt (records are marked, not deleted)
  • Uniform INVALID_CREDENTIALS error — does not reveal whether the email exists or the password is wrong
  • DTOs with class-validator and @Transform for input normalization

Configuration options

JWT: Access + Refresh vs Access token only

Access token only Access + Refresh
Complexity Minimal Full
Expiry Long-lived token (~24h) Short access (~15min) + long refresh
Remote revocation No Yes — revokedAt in DB
Best for Internal APIs, MVPs SaaS, mobile apps, production

Rate limiting: In-Memory vs Redis

In-Memory Redis
Setup Zero extra config Requires Redis
Scaling Single instance Multiple instances + load balancer
Best for Single server, development Horizontal production

ThrottlerGuard is registered as APP_GUARD inside AuthModule — it applies to the entire app once you import AuthModule. Default limits: 5 req/min on /auth/login, 10 req/min everywhere else.

To exclude routes use @SkipThrottle():

import { SkipThrottle } from '@nestjs/throttler';

@Get('health')
@SkipThrottle()
check() { return { status: 'ok' }; }

Environment variables

The CLI generates .env.example. Copy it and fill in your values:

cp .env.example .env
NODE_ENV=development
PORT=3000
APP_URL=http://localhost:3000
FRONTEND_URL=http://localhost:3001

# JWT — minimum 32 characters (validated on startup)
JWT_ACCESS_SECRET=change_me_to_a_secret_with_at_least_32_chars
JWT_ACCESS_EXPIRES=15m

# Access + Refresh only
JWT_REFRESH_SECRET=another_secret_with_at_least_32_characters
JWT_REFRESH_EXPIRES=7d

# Database
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=postgres
DB_NAME=postgres

# Rate limiting + Redis only
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=change_me

Post-install checklist

# 1. Install dependencies (the CLI prints the exact command when it finishes)
pnpm add @nestjs/passport passport passport-jwt @nestjs/jwt ...

# 2. Set up environment variables
cp .env.example .env

# 3. Import AuthModule and ConfigModule in app.module.ts

# 4. Start the database
docker compose up -d

# 5. Create the auth schema in PostgreSQL
docker compose exec postgres psql -U postgres -d postgres -c "CREATE SCHEMA auth;"

# 6. Run migrations
pnpm typeorm migration:run

# 7. Test
curl -X POST http://localhost:3000/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"test@example.com","password":"password123"}'

Steps 3–7 are detailed with full code in the README-AUTH.md generated in your project.


Local development

git clone https://github.com/dylantovar/nestjs-auth-kit.git
cd nestjs-auth-kit
pnpm install
pnpm build

# Test against a clean NestJS project
cd /path/to/your-nestjs-project
node /path/to/nestjs-auth-kit/dist/index.js init

CLI stack

Dependency Role
commander Command parsing
inquirer Interactive prompts
ejs Template engine
chalk Colored output
ora Loading spinners
fs-extra File writing

Repository structure

nestjs-auth-kit/
├── src/
│   ├── index.ts
│   ├── commands/init.ts
│   ├── prompts/questions.ts
│   ├── generators/
│   │   ├── template.renderer.ts   # Shared EJS engine
│   │   ├── config.generator.ts    # src/config/* + .env.example
│   │   ├── auth.generator.ts      # src/modules/auth/*
│   │   └── docker.generator.ts    # docker-compose.yml
│   └── templates/
│       ├── config/
│       ├── docker/
│       ├── dto/
│       ├── guards/
│       ├── decorators/
│       ├── strategies/
│       ├── enums/
│       └── orm/typeorm/
├── package.json
├── tsconfig.json
└── README.md

Roadmap

  • TypeORM + PostgreSQL
  • JWT Access + Refresh with rotation and revocation
  • RBAC with custom roles
  • Rate limiting (In-Memory / Redis)
  • Docker Compose
  • .env.example + Joi validation
  • Prisma support
  • Automatic app.module.ts modifiers
  • Generation tests + CI
  • npm publish

License

MIT

About

A powerful CLI scaffolder to generate production-ready authentication modules for NestJS projects. Includes JWT strategies, guards, and database wiring out of the box.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages