Stytch NestJS Starter
August 19, 2025 ยท View on GitHub
A production-ready NestJS backend starter with Stytch authentication integration
๐ Overview
This starter template provides a robust, production-ready NestJS backend with Stytch authentication integration. Instead of building authentication from scratch (which is complex and risky), this template leverages Stytch's secure, battle-tested authentication platform.
โจ Features
- ๐ Complete Stytch Integration: Email/password authentication with session management
- ๐๏ธ NestJS Best Practices: Modular architecture, guards, interceptors, and decorators
- ๐พ Redis Session Caching: Optimized session verification without hitting Stytch on every request
- ๐ Smart Session Refresh: Automatic session extension based on configurable thresholds
- ๐ Admin User Creation: Master key protected endpoints for creating users
- ๐ณ Docker Ready: Complete Docker setup with PostgreSQL and Redis
- ๐ TypeScript: Full type safety throughout the application
- ๐งช Testing Ready: Jest configuration included
- ๐ Database Migrations: TypeORM with migration support
๐๏ธ Architecture
Authentication Flow
sequenceDiagram
participant C as Client
participant API as NestJS API
participant R as Redis
participant S as Stytch
participant DB as PostgreSQL
C->>API: POST /auth/login
API->>S: Authenticate user
S-->>API: Session token + user data
API->>DB: Get/create user record
API->>R: Cache session with TTL
API-->>C: Return session token
Note over C,DB: Subsequent requests
C->>API: GET /resources (Bearer token)
API->>R: Check cached session
R-->>API: Return user session
API-->>C: Return protected data
Note over C,DB: Session refresh
API->>S: Extend session (if threshold met)
S-->>API: New session token
API->>R: Update cache
API-->>C: New token in X-New-Session-Token header
System Architecture
graph TB
C[Client Application] --> API[NestJS API Server]
API --> R[Redis Cache]
API --> DB[PostgreSQL Database]
API --> S[Stytch Service]
๐ Quick Start
Prerequisites
- Node.js 22+ and Yarn
- Docker and Docker Compose
- Stytch account (sign up here)
1. Clone and Install
git clone https://github.com/u11d-com/stytch-nestjs-react-starter.git
cd stytch-nestjs-react-starter
yarn install
2. Environment Setup
cp .env.example .env
Configure your .env file which will be used for local development.
3. Start Infrastructure
# Start PostgreSQL and Redis
docker compose up postgres redis -d
# Run database migrations
yarn migration:run
4. Start Development Server
yarn start:dev
Your API will be available at http://localhost:3000
๐ Available Scripts
| Script | Description |
|---|---|
yarn start:dev | Start development server with hot reload |
yarn build | Build the application |
yarn start:prod | Start production server |
yarn migration:generate | Generate new database migration |
yarn migration:run | Run pending migrations |
yarn create-user <email> | Create admin user (sends magic link) |
yarn test | Run unit tests |
yarn test:e2e | Run end-to-end tests |
yarn lint | Lint and fix code |
๐ Authentication Endpoints
Public Endpoints
| Method | Endpoint | Description |
|---|---|---|
POST | /auth/sign-up | Create new user account |
POST | /auth/login | Authenticate user |
POST | /auth/password | Set password using magic link token |
Protected Endpoints
| Method | Endpoint | Description | Auth |
|---|---|---|---|
POST | /auth/refresh | Refresh session token | Bearer |
POST | /auth/logout | Revoke session | Bearer |
GET | /resources | Access protected resources | Bearer |
Admin Endpoints
| Method | Endpoint | Description | Auth |
|---|---|---|---|
POST | /auth/invite | Create user and send magic link | Master Key |
๐ Authentication Methods
1. Self Sign-up
Users can create their own accounts:
curl -X POST http://localhost:3000/auth/sign-up \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "SecurePassword123!",
"firstName": "John",
"lastName": "Doe"
}'
2. Admin User Creation
Admins can invite users (sends magic link email) using master key:
# One can use predefined script
yarn create-user admin@company.com
# ...or execute the endpoint manually
curl -X POST http://localhost:3000/auth/invite \
-H "Content-Type: application/json" \
-H "X-Api-Key: your-master-key" \
-d '{
"email": "newuser@company.com",
"firstName": "Jane",
"lastName": "Smith"
}'
๐ Session Management
Caching Strategy
- Sessions are cached in Redis for fast verification
- Cache TTL matches Stytch session duration
- No Stytch API calls on every request = better performance
Smart Refresh
The system automatically refreshes sessions when they're close to expiring:
- Set
STYTCH_SESSION_REFRESH_THRESHOLD_MINUTES(default: 30) - If session expires within threshold, it's automatically extended
- New token returned in
X-New-Session-Tokenheader - Frontend should watch for this header and update stored token
Making Authenticated Requests
curl -X GET http://localhost:3000/resources \
-H "Authorization: Bearer your-session-token"
๐ณ Docker Deployment
# Copy and configure Docker environment
cp .env.example .env.docker
# Start all services
docker compose up -d
# Check logs
docker compose logs -f server
โ๏ธ Configuration
Session Duration
Control how long sessions last:
STYTCH_SESSION_DURATION_MINUTES=60 # Sessions expire after 1 hour
Session Refresh Threshold
Control when sessions are automatically refreshed:
STYTCH_SESSION_REFRESH_THRESHOLD_MINUTES=30 # Refresh when <30min left
Cache Provider
To use a different cache provider, update the CacheModule configuration in app.module.ts:
CacheModule.register({
// Your cache configuration
});
๐ง Customization
Adding User Roles
- Add role column to User entity
- Include role in cached session
- Create role-based guards
- Apply role guards to controllers
Adding 2FA
- Enable 2FA in Stytch dashboard
- Update authentication flow
- Add 2FA verification endpoints
๐ Extensions & Roadmap
Potential extensions (let us know if you're interested!):
- ๐ Role-based Access Control (RBAC)
- ๐ฑ SMS/Phone Authentication
- ๐ Multi-Factor Authentication (MFA)
- ๐ Social Login (Google, GitHub, etc.)
- ๐ง Email Templates & Customization
- ๐ Analytics & Monitoring Integration
- ๐ Webhook Support
๐ Troubleshooting
-
Stytch Configuration Errors
- Verify
STYTCH_PROJECT_IDandSTYTCH_SECRETare correct - Check Stytch dashboard for API key status
- Verify
-
Database Connection Issues
- Ensure PostgreSQL is running:
docker compose up postgres -d - Run migrations:
yarn migration:run
- Ensure PostgreSQL is running:
-
Redis Connection Issues
- Ensure Redis is running:
docker compose up redis -d - Check
REDIS_URLconfiguration
- Ensure Redis is running:
-
Session Issues
- Check session hasn't expired
- Verify token format:
Bearer <token> - Check Redis for cached session
๐ค Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/my-feature - Make your changes and add tests
- Commit your changes:
git commit -am 'Add some feature' - Push to the branch:
git push origin feature/my-feature - Submit a pull request
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
- Stytch for providing secure authentication infrastructure
- NestJS for the amazing framework
- The open-source community for inspiration and tools
Made with โค๏ธ by u11d
