A robust NestJS template providing secure, cookie-based authentication with Prisma, Docker, and Bun.
Report Bug
·
Request Feature
- Overview
- Features
- Architecture
- Prerequisites
- Installation
- Usage
- Configuration
- Database Schema
- API Reference
- Screenshots
- Tech Stack
- Contributing
- License
- Roadmap
- Acknowledgements
In modern web development, establishing a secure and efficient authentication system is paramount. This project, nestjs-prisma-auth, serves as a comprehensive template designed to jumpstart your NestJS applications with a robust, cookie-based JWT authentication solution.
It addresses the common challenge of integrating multiple technologies—NestJS for server-side logic, Prisma as an elegant ORM, PostgreSQL for data persistence, and Docker for environment consistency—into a cohesive and developer-friendly package. By providing a pre-configured setup with password hashing (Argon2), secure JWTs stored in HTTP-only cookies, and a streamlined development workflow using Bun, nestjs-prisma-auth significantly reduces setup time, allowing developers to focus on core application features from day one.
This template comes packed with a suite of features designed to provide a secure, efficient, and enjoyable development experience:
- Robust Authentication: Secure, cookie-based JWT (JSON Web Token) authentication strategy.
- Password Hashing: Utilizes
argon2for strong, industry-standard password hashing. - Database Management: Integrated with
Prisma ORMfor seamless interaction with aPostgreSQLdatabase. - Dockerized Environment:
docker-composesetup for easily spinning up a local PostgreSQL database. - Performance & Efficiency: Leverages
Bunas a fast JavaScript runtime and package manager. - Modular Architecture: Follows NestJS best practices with dedicated modules for
AuthandUsers. - API Documentation: Built-in
Swaggerdocumentation for clear API endpoint definitions and testing. - Input Validation: Global
ValidationPipewithclass-validatorandclass-transformerfor robust data integrity. - Testing Suite: Includes
Jestfor unit and end-to-end testing, withPactumfor API contract testing. - Code Quality: Enforced with
ESLintandPrettierfor consistent and maintainable code. - Environment Management: Flexible
.envfile handling withdotenvanddotenv-clifor different environments (development, test).
The nestjs-prisma-auth application follows a modular and layered architecture, typical for NestJS projects, emphasizing separation of concerns and maintainability.
graph TD
A[Client Application] --> B(NestJS Application)
B --> C{Auth Module}
B --> D[Users Module]
C --> E[JWT Strategy]
C --> F(Argon2 for Hashing)
C -- Authenticates --> D
D --> G(Prisma Service)
G --> H[PostgreSQL Database]
E -- Validates Token --> C
subgraph NestJS Core
B
C
D
G
end
subgraph Security Layer
E
F
end
subgraph Data Layer
G
H
end
style NestJS Core fill:#f9f,stroke:#333,stroke-width:2px
style Security Layer fill:#ccf,stroke:#333,stroke-width:2px
style Data Layer fill:#cfc,stroke:#333,stroke-width:2px
- Client Application: Interacts with the NestJS application via HTTP requests.
- NestJS Application: The core of the backend, orchestrating requests and responses. It serves as the entry point and routes requests to appropriate modules.
- Auth Module: Handles user authentication, including registration (
signUp), login (signIn), JWT generation, and cookie management. It relies on theJWT StrategyandArgon2for security. - Users Module: Manages user-related operations, interacting directly with the
Prisma Serviceto perform CRUD operations on user data. It's often used by theAuth Moduleafter successful authentication to retrieve user details. - JWT Strategy: A Passport.js strategy responsible for extracting and validating JSON Web Tokens, typically from HTTP-only cookies.
- Argon2 for Hashing: Used within the
Auth Moduleto securely hash user passwords before storing them in the database. - Prisma Service: A singleton service that encapsulates the Prisma Client, providing a centralized and efficient way to interact with the database.
- PostgreSQL Database: The relational database used for persistent storage of application data, including user accounts.
This architecture ensures a clear flow of data and responsibilities, promoting scalability and ease of debugging.
Before you begin, ensure you have the following installed on your system:
- Bun: A fast all-in-one JavaScript runtime.
- Docker & Docker Compose: For managing the PostgreSQL database.
Follow these steps to get your development environment up and running:
-
Clone the repository:
git clone https://github.com/mrrmartin01/nestjs-prisma-auth.git cd nestjs-prisma-auth -
Create environment file: Copy the example environment file and update it with your configuration (e.g.,
DATABASE_URL,JWT_SECRET).cp .env.example .env # Open .env and configure your variablesMake sure to change
YOUR_SECRET_KEYin.envto a strong, random string. -
Start the local PostgreSQL database: This command uses Docker Compose to spin up a PostgreSQL container in detached mode (
-d).bun db:dev:up
-
Deploy Prisma migrations: Apply the database schema to your local PostgreSQL instance.
bun prisma:dev:deploy
-
Install dependencies: Use Bun to install all project dependencies.
bun install
-
Start the application in development mode:
bun start:dev
The application will be running on
http://localhost:3000(or your configuredPORT).
-
Development Mode:
bun start:dev
The application will watch for file changes and restart automatically.
-
Production Mode: First, build the application:
bun build
Then, start the compiled application:
bun start:prod
Once the application is running, the interactive API documentation powered by Swagger UI can be accessed at:
http://localhost:3000/api/docs
This interface allows you to explore all available endpoints, view expected request/response formats, and even send requests directly from your browser.
-
Unit/Integration Tests:
bun test -
End-to-End Tests: This will spin up a separate test database, run the tests, and then tear down the database.
bun test:e2e
All environment-specific configurations are managed through .env files. A .env.example is provided to guide you.
Key environment variables to configure:
| Variable | Description | Default Value |
|---|---|---|
PORT |
The port on which the NestJS application will listen. | 3000 |
DATABASE_URL |
Connection string for the PostgreSQL database (e.g., postgresql://user:password@host:port/database). |
postgresql://user:password@localhost:5432/nestjsauth?schema=public |
JWT_SECRET |
A strong, secret key used for signing and verifying JWTs. CRITICAL FOR SECURITY. | YOUR_SECRET_KEY |
JWT_EXPIRATION_TIME |
Expiration time for JWTs (e.g., 1h, 7d). |
1h |
NODE_ENV |
Environment mode (development, production, test). |
development |
Important: Ensure JWT_SECRET is a strong, random, and confidential string in production environments.
The project uses Prisma ORM to define and manage the database schema. The primary entity is the User.
// prisma/schema.prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
email String @unique
hash String // Stores the Argon2 hashed password
firstName String?
lastName String?
}This schema defines a User model with essential fields for authentication and user profiles:
id: Unique identifier for the user.createdAt,updatedAt: Timestamps for record creation and last update.email: User's email, which must be unique.hash: The securely hashed password.firstName,lastName: Optional fields for user's first and last name.
The API provides endpoints for user authentication and basic user management. All endpoints are prefixed with /api.
| Method | Endpoint | Description | Request Body | Response Status | Response Body (Success) |
|---|---|---|---|---|---|
POST |
/auth/signup |
Registers a new user. | CreateUserDto |
201 Created |
User object (without hash) |
POST |
/auth/signin |
Authenticates a user and sets a JWT cookie. | SignInDto |
200 OK |
User object (without hash) |
POST |
/auth/signout |
Clears the JWT cookie and logs out the user. | N/A |
200 OK |
{ message: 'Logged out successfully' } |
CreateUserDto
{
"email": "string",
"password": "string",
"firstName"?: "string",
"lastName"?: "string"
}SignInDto
{
"email": "string",
"password": "string"
}| Method | Endpoint | Description | Authentication | Response Status | Response Body (Success) |
|---|---|---|---|---|---|
GET |
/users/me |
Retrieves the profile of the authenticated user. | JWT Bearer |
200 OK |
User object (without hash) |
PATCH |
/users/me |
Updates the profile of the authenticated user. | JWT Bearer |
200 OK |
User object (without hash) |
Note: All authenticated endpoints require a valid JWT in an HttpOnly cookie. The Swagger UI can handle this automatically after a successful signIn.
This project leverages a modern and powerful set of technologies:
- Backend Framework: NestJS (v11.x) - A progressive Node.js framework for building efficient, reliable, and scalable server-side applications.
- Database: PostgreSQL - A powerful, open-source object-relational database system.
- ORM: Prisma (v6.x) - Next-generation ORM for Node.js and TypeScript.
- Language: TypeScript (v5.x) - A typed superset of JavaScript that compiles to plain JavaScript.
- Runtime/Package Manager: Bun - An incredibly fast all-in-one JavaScript runtime, bundler, test runner, and package manager.
- Authentication:
- Passport.js (v0.7.x) - Simple, unobtrusive authentication for Node.js.
- JWT (JSON Web Tokens) - For secure information exchange between parties.
- Argon2 (v0.44.x) - A strong password hashing function.
- Cookie-Parser (v1.4.x) - Parse Cookie header and populate
req.cookies.
- Validation: Class-Validator (v0.14.x) & Class-Transformer (v0.5.x) - For declarative validation and transformation of objects.
- API Documentation: Swagger (OpenAPI) via
@nestjs/swagger(v11.x). - Testing:
- Linting & Formatting: ESLint (v9.x) & Prettier (v3.x).
- Containerization: Docker & Docker Compose - For containerized development environment.
We welcome contributions from the community! Whether it's a bug report, a new feature, or improving documentation, your help is appreciated. Please take a moment to review the following guidelines.
If you find a bug, please open an issue on the GitHub repository. When reporting a bug, please include:
- A clear and concise description of the bug.
- Steps to reproduce the behavior.
- Expected behavior.
- Screenshots or error messages, if applicable.
- Your operating system, Node.js/Bun version, and any other relevant environment details.
Have an idea for a new feature or improvement? Open an issue on the GitHub repository with the label feature-request.
Please provide:
- A clear and concise description of the proposed feature.
- The problem it solves or the benefit it provides.
- Any potential design considerations or alternatives.
- Fork the repository: Click the "Fork" button at the top right of this repository's page.
- Clone your forked repository:
git clone https://github.com/YOUR_USERNAME/nestjs-prisma-auth.git cd nestjs-prisma-auth - Create a new branch:
git checkout -b feature/your-feature-name-or-bugfix/issue-number
- Set up environment:
- Ensure Bun and Docker are installed (see Prerequisites).
- Copy
.env.exampleto.envand configure your settings. - Start the development database:
bun db:dev:up - Deploy Prisma migrations:
bun prisma:dev:deploy - Install dependencies:
bun install
- Start the development server:
bun start:dev - Make your changes: Implement your feature or fix.
- Write tests: Ensure your changes are covered by appropriate unit or E2E tests.
- Run tests:
bun testandbun test:e2eto ensure everything works as expected. - Format and Lint: Ensure your code adheres to project standards:
bun format bun lint
- Follow the existing code style. The project uses Prettier and ESLint, which can automatically format and lint your code.
- Use meaningful variable and function names.
- Keep functions and methods small and focused on a single responsibility.
- Add comments where the code isn't self-explanatory.
- Adhere to NestJS best practices regarding module, service, and controller structure.
- Commit your changes: Write clear and concise commit messages.
git add . git commit -m "feat: Add new user registration endpoint"
- Push your branch to your GitHub fork:
git push origin feature/your-feature-name
- Open a Pull Request:
- Go to the original
nestjs-prisma-authrepository on GitHub. - You should see a "Compare & pull request" button for your recently pushed branch.
- Provide a clear title and description for your pull request.
- Reference any related issues (e.g.,
Fixes #123,Closes #456).
- Go to the original
- Await Review: Project maintainers will review your code. Be prepared to address feedback and make further changes if necessary.
This is a simplified representation of the Pull Request workflow:
gitGraph
commit id: "Initial commit"
branch feature/my-new-feature
checkout feature/my-new-feature
commit id: "Implement signup DTO"
commit id: "Add signup controller logic"
commit id: "Write unit tests for signup"
checkout main
commit id: "Hotfix: Security patch"
checkout feature/my-new-feature
merge main id: "Merge upstream/main"
commit id: "Address review comments"
checkout main
merge feature/my-new-feature id: "Pull Request Merge (feature/my-new-feature)"
tag "v0.0.1"
This project is licensed under the MIT License.
MIT License
Copyright (c) 2025 mrrmartin01
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
- Implement JWT refresh tokens for extended session management.
- Add integration tests for all authentication flows.
- Implement password reset functionality (forgot password flow).
- Add email verification for new user registrations.
- Integrate role-based access control (RBAC) with decorators.
- Expand user management endpoints (e.g.,
GET /users,DELETE /users/:id). - Add GraphQL support.
- Dockerize the entire NestJS application for production deployment.
- Set up CI/CD pipeline for automated testing and deployment.
- Improve error handling and logging mechanisms.
- NestJS - The superb framework that powers this project.
- Prisma - For making database interactions a breeze.
- Docker - For simplifying environment setup.
- Bun - For revolutionizing JavaScript tooling speed.
- Swagger - For excellent API documentation.
- Shields.io - For the awesome badges.
- Mermaid.js - For powerful diagrams in markdown.
📝 Generated with DocSage - AI-powered documentation