Skip to content
Projetos

andrechristikan/ack-nestjs-boilerplate

Ver no GitHub

Sobre

Boilerplate NestJS 12 com JWT, OAuth (Google e Apple), TOTP/2FA, RBAC e multitenancy com vários workspaces. Prisma no MongoDB, camada de repositório modular, ESM nativo. Pronto para produção.

Segurança e privacidade

Como estes números são medidos

O que você pode fazer

  • Login with biometrics (fingerprint or face detection)
  • Login with passkey
  • Login with Github SSO
  • Mobile number verification by WhatsApp and/or SMS

Crescimento medido de estrelas

em 24 h
0
em 7 dias
+1
em 15 dias
+2
em 1 mês
Coletando histórico

Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.

README.md

Original

Contributors Forks Stargazers Issues MIT License

NestJs NodeJs Typescript MongoDB JWT Vitest PNPM Docker

ACK NestJs Boilerplate 🔥 🚀

ACK NestJs is a NestJs v12.x boilerplate with JWT, OAuth (Google & Apple), TOTP/2FA, and RBAC. It runs Prisma on MongoDB (replica set required), uses native ESM, and stays modular with a repository layer for data access.

Request a feature or report a bug.

Ideal For

A good fit when you are building:

  • 🏢 Enterprise apps - Auth with roles, CASL policies, and an activity log
  • 🔐 Auth services - JWT, Google and Apple sign-in, and TOTP 2FA
  • 📱 Mobile backends - REST API with social login, device tracking, and push notifications
  • 🌐 Multi-tenant SaaS - Every user belongs to a workspace; projects stay workspace-scoped, with invites and join requests
  • 💼 Startup MVPs - Auth, workspaces, notifications, and file upload already wired

Table of Contents

Important

  • MongoDB must run as a replica set; Prisma transactions need it.

  • When APP_ENV is production, Swagger is off, and Sentry Logs only get warn, error, and fatal (other environments send every level).

  • Protection decorators follow a fixed stack. Use only the ones you need, and keep that relative order. Activity logging is separate: domains stage events, and a global interceptor writes them.

    @Doc({ summary: '…' })
    @Response('example.get')          // or @ResponsePagination / @ResponseFile
    @TermPolicyAcceptanceProtected(...)
    @PolicyProtected({...})
    @RoleProtected(...)
    @ProjectMemberProtected(...)      // never on /admin
    @ProjectProtected()               // never on /admin
    @WorkspaceMemberProtected(...)    // never on /admin
    @WorkspaceProtected()             // never on /admin
    @UserProtected()
    @FeatureFlagProtected(...)
    @AuthJwtAccessProtected()
    @ApiKeyProtected()
    @Get('/some-endpoint')
    

    Nest runs the stack bottom-up, so a decorator that needs state from another one sits above it:

    • @FeatureFlagProtected() sits above @AuthJwtAccessProtected() so the flag guard can see request.user
    • if you flip that order, there is no user yet, targetUserIds is skipped, and rollout keys off the anonymous-ID header instead

    Full detail: Authorization Documentation.

TODO

  • Move to PostgreSQL
  • Move to a monorepo (backend application and a separate documentation website)

Next Features

  • Login with biometrics (fingerprint or face detection)
  • Login with passkey
  • Login with Github SSO
  • Mobile number verification by WhatsApp and/or SMS
  • Versioning System (force the frontend to update, especially mobile)

Prerequisites

You will get more out of this project if you already know:

  1. NestJs Fundamentals - Decorators, modules, services, and dependency injection
  2. TypeScript - Strong typing, interfaces, and generics
  3. Prisma ORM - Schema design, prisma db push, and type-safe queries
  4. MongoDB - NoSQL basics, especially replica sets for transactions
  5. Redis - Caching, session storage, and queues
  6. Repository Design Pattern - Keeping data access behind a clear layer
  7. SOLID Principles - Clean architecture and dependencies
  8. Queue Systems - Background jobs with BullMQ
  9. Docker (optional) - Handy for running the local stack

Build with

Versions this project expects:

Name Version
NestJs v12.x
NodeJs >= 24.15.0
PNPM >= 10.25.0 (pin [email protected])
TypeScript v6.0.x
Prisma v6.19.x
MongoDB v8+ (compose: mongo:latest)
Redis v8+ (compose: redis:latest)
Docker v28.5.x+
Docker Compose v2.40.x+

See package.json for the full list.

Objective

  • Modular, component-based folder structure
  • Stateful authentication and authorization
  • Repository Design Pattern
  • Twelve-Factor App practices
  • Native ESM
  • Multi-workspace tenancy with workspace-scoped projects

Features

🔐 Authentication & Security

  • JWT + stateful sessions - ES256 access and ES512 refresh tokens, Redis-backed sessions, and instant revocation
  • Social sign-in - Google OAuth and Apple Sign In for mobile and web
  • TOTP 2FA - Authenticator apps, encrypted secrets, and backup recovery codes
  • RBAC & CASL policies - Roles and fine-grained abilities on top of workspace and project membership
  • API keys & rate limits - x-api-key guards plus Redis sliding-window limits (per IP, per user, per route)

🌐 Workspaces & Projects

  • Multi-workspace tenancy - Every user gets a workspace; personal by default, or the inviting workspace when they join through an invite
  • Projects inside workspaces - Membership, invites, and join requests, with a feature flag when you want the surface off
  • Feature flags - On/off, target users, and percentage rollout by user or anonymous ID

📊 Database & Storage

  • Prisma on MongoDB - Type-safe queries with replica-set transactions
  • Redis cache - Shared across instances, with configurable TTLs
  • AWS S3 - Presigned upload and download for public and private buckets
  • Offset & cursor pagination - List endpoints that still feel fast as data grows

🔔 Notifications

  • Multi-channel delivery - Email, push, in-app, and silent, with per-type and per-channel preferences
  • AWS SES + Firebase FCM - Templated email and multicast push, including token cleanup
  • BullMQ workers - Async delivery and other background jobs in the same process as the API

📖 Notification Documentation covers setup and usage.

📈 Analytics

  • Activity log - Domains stage user actions; a global interceptor writes them after the request settles (including actor/target pairs)
  • Analytic dashboard - Admin metrics, anomaly and fraud reports, and current-workspace user metrics (docs)

🩺 Monitoring

  • Sentry - Errors, performance, and Pino logs, with credentials scrubbed before send
  • Health checks - /system/health for database, AWS, third-party, and instance status

🛠 Development

  • NestJS 12 + TypeScript 6 - Strict mode, SWC builds, and hot reload next to a typecheck
  • OpenAPI 3.1 - Swagger UI and generated/swagger.json from the same route schemas (off in production)
  • Zod contracts - Request and response shapes checked end to end
  • i18n - Localized messages via x-custom-lang
  • Vitest - Unit suite under test/; pnpm test:cov aims for full coverage
  • Lint & hooks - ESLint (incl. security), Prettier, cspell, knip, Husky, and commitlint
  • Docker Compose - MongoDB replica set, Redis, BullBoard, and JWKS locally; optional apis and vault profiles
  • HashiCorp Vault - Optional secret sync into .env (docs)
  • Docs - 30+ guides, including the status code catalog

Quick Start

# Clone repository
git clone https://github.com/andrechristikan/ack-nestjs-boilerplate

# Install dependencies
pnpm install

# Setup environment
cp .env.example .env

# Generate JWT keys and encryption secrets into .env
pnpm generate:secret --direct-insert

# Generate the Prisma client and src/generated/package/package.ts
pnpm generate

# Start infrastructure (MongoDB + Redis + BullBoard + JWKS)
docker-compose up -d

# Push the schema (MongoDB replica set must already be up)
pnpm db:migrate

# Run the API on the host
pnpm start:dev

Swagger UI: http://localhost:3000/docs.

Want the API inside Compose too? Use the apis profile: docker-compose --profile apis up -d.

Database

This boilerplate uses MongoDB (prisma/schema.prisma provider = "mongodb"). Prisma transactions need a replica set.

  • Schema sync: pnpm db:migrate (prisma db push)
  • No prisma migrate history; shape changes go through db push
  • ObjectId helpers, transactions, and seeds assume MongoDB

PostgreSQL is on the TODO. Setup and seeding: Database Documentation.

Installation

Docker is the recommended setup. Step-by-step (Compose first, then Atlas + Redis if you cannot use Docker): Installation.

License

MIT License.

Contribute

Contributions are welcome. Start with CONTRIBUTING.md.

Contact

Andre Christi Kan
📧 [email protected]

Github LinkedIn

Support This Project

If this boilerplate helped you, buy me a coffee to keep this project alive.

Or via PayPal

Explore projetos relacionados

Carregando…