@astralicc/create-nestjs-auth-swagger
v2.6.1
Published
CLI tool to scaffold a production-ready NestJS authentication system with JWT, refresh tokens, and RBAC
Maintainers
Readme
@astralicc/create-nestjs-auth-swagger
The Zero-Config Way to Build Secure Authentication & CRUD APIs
Stop wasting 40 hours building JWT auth & CRUD modules from scratch.
Get a battle-tested, production-ready NestJS auth system and Swagger-documented APIs in under 3 minutes.
npx @astralicc/create-nestjs-auth-swagger@latestQuick Start | ORM & Database Options | Features | Docs
v2.4.0 | Interactive Module Generator | Swagger UI Included | 4 ORMs | 4 Databases
Why This Exists
Building secure JWT authentication and standard CRUD operations isn't trivial. You need:
- Access tokens + refresh token rotation
- HttpOnly cookies (not localStorage)
- Multi-device session management
- Role-based access control (RBAC)
- Rate limiting & brute-force protection
- PII-safe logging
- Proper password hashing (bcrypt 12 rounds)
- Flexible ORM & database choices
- Consistent, secure CRUD boilerplate with strict validation
- Automated API Documentation (Swagger)
This CLI gives you all of that. Production-ready, security-hardened, tested patterns - instantly.
The Problem with Building APIs From Scratch
| Task | Time Required | Complexity | |------|---------------|------------| | JWT access/refresh setup | 6-8 hours | High | | Token rotation logic | 4-6 hours | Very High | | RBAC implementation | 3-4 hours | Medium | | Rate limiting | 2-3 hours | Medium | | Security hardening | 8-10 hours | Very High | | Base CRUD & Swagger setup | 5-7 hours | Medium | | Testing & debugging | 6-8 hours | High | | Total | 34-46 hours | **** |
With @astralicc/create-nestjs-auth-swagger
| Task | Time Required | Complexity | |------|---------------|------------| | Run one command | 3 minutes | Zero | | Generate new modules | 10 seconds | Zero | | Total | ~3 minutes | **** |
Save 40+ hours and get battle-tested code that just works.
Quick Start
30 seconds to a running auth API with Swagger Docs:
# Run the CLI
npx @astralicc/create-nestjs-auth-swagger@latest
# Answer quick questions
# Project name
# ORM (Prisma, Drizzle, TypeORM, or Mongoose)
# Database (PostgreSQL, MySQL, SQLite, or MongoDB)
# Enable Base CRUD Architecture? (Yes/No)
# Package manager
# Install dependencies
# Setup database
# Initialize git
# Done! Your API is running at http://localhost:8080/api/v1
# Swagger UI is available at http://localhost:8080/api/docscreate-nestjs-auth-swagger
? What is your project name? my-awesome-api
? Which ORM would you like to use? Prisma
? Which database would you like to use? PostgreSQL
? Enable Base CRUD Architecture? Yes
? Which package manager? pnpm (detected)
? Install dependencies? Yes
? Initialize git repository? Yes
Creating my-awesome-api...
Installing dependencies...
Success! Created my-awesome-api
? Complete setup now? Yes
Generating JWT secrets...
? Enter PostgreSQL URL: postgresql://localhost:5432/mydb
? Set up database now? Yes
Running migrations & seed...
Default admin: [email protected] / Admin@123
? Start dev server? Yes
Server running at http://localhost:8080/api/v1
Swagger UI at http://localhost:8080/api/docsWhat You Get
Enterprise-Grade Security
- Token Rotation - Refresh tokens auto-rotate on use
- Zero XSS Risk - HttpOnly cookies only
- Bcrypt 12 Rounds - 2025 security baseline
- Rate Limiting - 5 auth attempts/min
- PII-Safe Logs - Passwords/tokens auto-redacted
- Mass Assignment Protection -
ValidationPipewithwhitelist: true&forbidNonWhitelisted: true - Strict Parameter Parsing -
@ParseUUIDPipe/@ParseIntPipeon ID parameters.
Developer Experience
- Interactive Module Generator - Scaffold CRUD in seconds
- Auto-Generated Swagger Docs - Out-of-the-box UI at
/api/docs - TypeScript - Full type safety
- Base CRUD Architecture - Abstract
BaseService&BaseController - Hot Reload - Instant feedback
- Prisma Studio - Visual database UI
Production-Ready
- RBAC in 2 Lines -
@Roles(UserRole.ADMIN) - Multi-Device Sessions - Track 5 devices/user
- Structured Logging - Pino JSON logs
- Input Validation - Zod + class-validator
- CORS & Helmet - Security headers included
- Global Error Handling - Handled
NotFoundExceptionand Soft-Deletes.
Flexible Database Support
- 4 ORMs - Prisma, Drizzle, TypeORM, Mongoose
- 4 Databases - PostgreSQL, MySQL, SQLite, MongoDB
- Type-Safe - Full TypeScript support across all ORMs
- Migrations - Version control for your database
- Seeding - Default admin user included
Interactive Module Generator
Add new CRUD modules dynamically to your running project anytime using the generate (or g) sub-command!
# Inside your project directory
npx @astralicc/create-nestjs-auth-swagger g [module-name]
# OR
npx @astralicc/create-nestjs-auth-swagger generate [module-name]Interactive Prompts
- Module Name: If not provided via CLI args, you'll be prompted:
"What module do you want to generate?" - CRUD Mode Selection:
Full CRUD (Create, Read All, Read One, Update, Delete)Custom Selection...
- Cherry-Pick Operations: If you select "Custom Selection", you can use a multiselect checkbox to pick exactly what you need (e.g., just
CreateandRead All).
Auto-Generated Files & Swagger Integration
The generator intelligently creates ORM-aware files for your module, fully wired with Swagger decorators:
module-name.controller.ts(Decorated with@ApiTags,@ApiOperation,@ApiResponse, etc.)module-name.service.ts(Uses the correct Repository implementation based on your active ORM)module-name.module.tsdto/create-module-name.dto.ts&update-module-name.dto.tsdto/module-name.dto.ts(With@ApiPropertydecorators for Swagger schemas)
Base CRUD Architecture & Security-Safe Features
During initial setup, if you select "Enable Base CRUD Architecture? (Y/n)", your project is scaffolded with a robust, abstract generic base for controllers and services.
BaseService&BaseController: Extensible classes that handle standard operations.- Security-First:
- Protects against Mass Assignment via strict
ValidationPipesettings (whitelist: true,forbidNonWhitelisted: true). - Ensures valid inputs via strict parameter parsing (e.g.,
@ParseUUIDPipe).
- Protects against Mass Assignment via strict
- Resilient: Built-in Soft-delete support and global
NotFoundExceptionhandling.
Auto-Generated Swagger Docs (@nestjs/swagger)
Say goodbye to manual API documentation!
- Swagger UI is enabled out-of-the-box and accessible at
/api/docs. - Every route scaffolded by the initial CLI setup or the
gsub-command comes pre-configured with@nestjs/swaggerdecorators. - DTOs automatically generate OpenAPI schemas using
@ApiPropertyand@ApiPropertyOptional. - Endpoint descriptions, expected parameters, and HTTP response codes are fully documented instantly.
See It in Action
60-Second Complete Setup
# 1. Create project (10 seconds)
npx @astralicc/create-nestjs-auth-swagger@latest my-api
# 2. Answer prompts (20 seconds)
# Project name: my-api
# ORM: Prisma (or Drizzle, TypeORM, Mongoose)
# Database: PostgreSQL (or MySQL, SQLite, MongoDB)
# Enable Base CRUD: Yes
# Package manager: pnpm
# Install dependencies: Yes
# Database URL: postgresql://localhost:5432/mydb
# Setup database: Yes
# Start server: Yes
# 3. Your API is live! (30 seconds)
# http://localhost:8080/api/v1
# http://localhost:8080/api/docs (Swagger UI)Live Example
# Login
curl -X POST http://localhost:8080/api/v1/auth/login \
-H "Content-Type: application/json" \
-c cookies.txt \
-d '{"email":"[email protected]","password":"Admin@123"}'
# Access protected route
curl http://localhost:8080/api/v1/auth/me -b cookies.txtWhat the Code Looks Like
Adding a protected admin endpoint (2 lines):
@Roles(UserRole.ADMIN) // Just add this decorator
@Delete('posts/:id')
deletePost() {
return { message: 'Deleted' };
}Getting the current user (1 line):
@Get('my-profile')
getProfile(@GetUser() user) { // User automatically injected
return { profile: user };
}Making an endpoint public (1 line):
@Public() // Skip authentication
@Get('posts')
findAll() {
return { posts: [] };
}That's it. No boilerplate. No configuration. Just decorators.
How It Works
The Magic Behind the CLI
graph LR
A[Run CLI] --> B[Interactive Setup]
B --> C[Generate Project]
C --> D[Install Dependencies]
D --> E[Generate JWT Secrets]
E --> F[Configure Database]
F --> G[Run Migrations]
G --> H[Seed Admin User]
H --> I[Start Dev Server & Swagger]
style A fill:#667eea
style I fill:#48bb78What Gets Created
my-app/
├── src/
│ ├── modules/
│ │ ├── auth/ # JWT + Refresh token logic
│ │ ├── users/ # User CRUD + profile
│ │ └── health/ # Health check endpoints
│ ├── common/
│ │ ├── base/ # Abstract BaseController & BaseService
│ │ ├── guards/ # JWT & RBAC guards
│ │ ├── decorators/ # @Roles(), @Public(), @GetUser()
│ │ └── filters/ # Exception handling
│ └── config/ # Environment & logging config
├── prisma/ # (Prisma) Schema + migrations + seed
├── drizzle/ # (Drizzle) Schema + migrations
├── test/ # E2E test suite
├── .env # Auto-configured secrets
└── package.json # All dependencies readyUsage Examples
1. Interactive Mode (Recommended)
Zero configuration. Just answer questions:
npx @astralicc/create-nestjs-auth-swagger@latest2. Automation Mode
For CI/CD and scripts:
# Skip all prompts, use defaults
npx @astralicc/create-nestjs-auth-swagger@latest my-app --yes
# Specify ORM and database
npx @astralicc/create-nestjs-auth-swagger@latest my-app --orm drizzle --database postgres --yesComplete API Reference
Your generated API includes these endpoints out of the box (fully documented in Swagger):
Authentication
| Endpoint | Method | Description | Auth |
|----------|--------|-------------|------|
| /auth/signup | POST | Register new user | |
| /auth/login | POST | Login with credentials | |
| /auth/refresh | POST | Refresh access token | Refresh token |
| /auth/logout | POST | Logout & invalidate tokens | |
| /auth/me | GET | Get current user | |
Users (Admin Only)
| Endpoint | Method | Description | Auth |
|----------|--------|-------------|------|
| /users | GET | List all users (paginated) | ADMIN |
| /users/:id | GET | Get user by ID | ADMIN |
| /users/:id | PATCH | Update user | ADMIN |
| /users/:id | DELETE | Soft delete user | ADMIN |
Profile
| Endpoint | Method | Description | Auth |
|----------|--------|-------------|------|
| /users/profile | GET | Get own profile | |
| /users/profile | PATCH | Update own profile | |
import { Controller, Get } from '@nestjs/common';
import { Roles } from '@/common/decorators/roles.decorator';
import { UserRole } from '@prisma/client';
@Controller('posts')
export class PostsController {
// Public endpoint - anyone can access
@Public()
@Get()
findAll() {
return { posts: [] };
}
// Protected endpoint - any authenticated user
@Get('my-posts')
getMyPosts(@GetUser() user) {
return { posts: [], userId: user.id };
}
// Admin only - requires ADMIN role
@Roles(UserRole.ADMIN)
@Delete(':id')
deletePost() {
return { message: 'Post deleted' };
}
}That's it! No manual guard setup. Just decorators.
CLI Options Reference
| Option | Description | Example |
|--------|-------------|---------|
| g [module] | Generate new CRUD module | npx @astralicc/create-nestjs-auth-swagger g products |
| --orm <orm> | Select ORM (prisma, drizzle, typeorm, mongoose) | npx @astralicc/create-nestjs-auth-swagger@latest my-app --orm drizzle |
| --database <db> | Select database (postgres, mysql, sqlite, mongodb) | npx @astralicc/create-nestjs-auth-swagger@latest my-app --database mysql |
| --yes | Skip all prompts, use defaults | npx @astralicc/create-nestjs-auth-swagger@latest my-app --yes |
| --skip-install | Don't install dependencies | npx @astralicc/create-nestjs-auth-swagger@latest my-app --skip-install |
| --package-manager <pm> | Force package manager (npm, pnpm, yarn, bun) | npx @astralicc/create-nestjs-auth-swagger@latest my-app --package-manager pnpm |
| --help | Show help message | npx @astralicc/create-nestjs-auth-swagger@latest --help |
System Requirements
| Requirement | Version | Why? | |------------|---------|------| | Node.js | >= 20.x | Native fetch, improved performance | | Database | PostgreSQL 16+, MySQL 8+, SQLite 3+, or MongoDB 6+ | Your choice! | | Package Manager | npm/pnpm/yarn/bun | Any works, auto-detected |
ORM & Database Options
Choose the combination that fits your project:
Supported ORMs
| ORM | Best For | Features | |-----|----------|----------| | Prisma | Most projects | Type-safe queries, visual studio, migrations | | Drizzle | SQL lovers | Lightweight, SQL-like syntax, fast | | TypeORM | Enterprise apps | Decorators, Active Record & Data Mapper | | Mongoose | MongoDB users | Schema validation, middleware, populate |
ORM + Database Compatibility
┌─────────────┬────────────┬───────┬────────┬─────────┐
│ │ PostgreSQL │ MySQL │ SQLite │ MongoDB │
├─────────────┼────────────┼───────┼────────┼─────────┤
│ Prisma │ ✅ │ ✅ │ ✅ │ ❌ │
│ Drizzle │ ✅ │ ✅ │ ✅ │ ❌ │
│ TypeORM │ ✅ │ ✅ │ ✅ │ ❌ │
│ Mongoose │ ❌ │ ❌ │ ❌ │ ✅ │
└─────────────┴────────────┴───────┴────────┴─────────┘Comparison with Alternatives
vs. Building from Scratch
| Feature | From Scratch | @astralicc/create-nestjs-auth-swagger |
|---------|-------------|-------------------|
| Time to setup | 34-46 hours | 3 minutes |
| Security audit | You do it (risky) | Battle-tested |
| Token rotation | Implement yourself | Included |
| RBAC | Build guards | Decorator-based |
| Rate limiting | Manual setup | Pre-configured |
| CRUD Generator | DIY | Included (g command) |
| Swagger Docs | Manual annotations | Auto-generated |
Troubleshooting
Use npx with @latest tag:
npx @astralicc/create-nestjs-auth-swagger@latest my-appReinstall the CLI:
npm uninstall -g @astralicc/create-nestjs-auth-swagger
npm cache clean --force
npm install -g @astralicc/create-nestjs-auth-swaggerCheck your PostgreSQL is running:
pg_isready
psql postgresql://user:password@localhost:5432/mydbOption 1: Change port in .env:
PORT=3000Contributing
We love contributions! Here's how you can help:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes
- Test thoroughly:
npm test - Commit:
git commit -m 'Add amazing feature' - Push:
git push origin feature/amazing-feature - Open a Pull Request
See CONTRIBUTING.md for detailed guidelines.
Tech Stack
| Technology | Version | Purpose | |------------|---------|---------| | NestJS | 11.0 | Progressive Node.js framework | | TypeScript | 5.7 | Type safety | | Prisma | 6.x | Type-safe ORM (option 1) | | Drizzle | Latest | Lightweight ORM (option 2) | | TypeORM | 0.3.x | Decorator-based ORM (option 3) | | Mongoose | 8.x | MongoDB ODM (option 4) | | Swagger | - | API Documentation | | Passport JWT | - | JWT authentication |
License
MIT License - do whatever you want with it!
See LICENSE for full details.
Did this save you time?
Star this repository to help others discover it!
Now go build something amazing!
