Stytch NestJS Starter

August 19, 2025 ยท View on GitHub

Stytch Logo

Stytch Logo

Nest Logo

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

ScriptDescription
yarn start:devStart development server with hot reload
yarn buildBuild the application
yarn start:prodStart production server
yarn migration:generateGenerate new database migration
yarn migration:runRun pending migrations
yarn create-user <email>Create admin user (sends magic link)
yarn testRun unit tests
yarn test:e2eRun end-to-end tests
yarn lintLint and fix code

๐Ÿ” Authentication Endpoints

Public Endpoints

MethodEndpointDescription
POST/auth/sign-upCreate new user account
POST/auth/loginAuthenticate user
POST/auth/passwordSet password using magic link token

Protected Endpoints

MethodEndpointDescriptionAuth
POST/auth/refreshRefresh session tokenBearer
POST/auth/logoutRevoke sessionBearer
GET/resourcesAccess protected resourcesBearer

Admin Endpoints

MethodEndpointDescriptionAuth
POST/auth/inviteCreate user and send magic linkMaster 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-Token header
  • 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

  1. Add role column to User entity
  2. Include role in cached session
  3. Create role-based guards
  4. Apply role guards to controllers

Adding 2FA

  1. Enable 2FA in Stytch dashboard
  2. Update authentication flow
  3. 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

  1. Stytch Configuration Errors

    • Verify STYTCH_PROJECT_ID and STYTCH_SECRET are correct
    • Check Stytch dashboard for API key status
  2. Database Connection Issues

    • Ensure PostgreSQL is running: docker compose up postgres -d
    • Run migrations: yarn migration:run
  3. Redis Connection Issues

    • Ensure Redis is running: docker compose up redis -d
    • Check REDIS_URL configuration
  4. Session Issues

    • Check session hasn't expired
    • Verify token format: Bearer <token>
    • Check Redis for cached session

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/my-feature
  3. Make your changes and add tests
  4. Commit your changes: git commit -am 'Add some feature'
  5. Push to the branch: git push origin feature/my-feature
  6. 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