A minimal, production-ready NestJS REST API demonstrating authentication with JWT and basic User CRUD using Mongoose. Includes validation, Docker setup, and Jest tests.
- Auth: Register, login, and protected
meroute via JWT - Users: Create, read, update, delete users (MongoDB + Mongoose)
- Validation:
class-validator+ globalValidationPipe - Config: Environment variables via
@nestjs/config - Testing: Unit and e2e tests with Jest and Supertest
- Docker:
Dockerfileanddocker-compose.ymlwith MongoDB service
- Runtime: Node.js
- Framework: NestJS 11
- Database: MongoDB (Mongoose 8)
- Auth: Passport JWT,
@nestjs/jwt - Validation:
class-validator,class-transformer - Testing: Jest, Supertest, mongodb-memory-server
- Lint/Format: ESLint 9, Prettier 3
- Clone and install
npm install- Create
.envin project root
PORT=3000
MONGO_URI=mongodb://localhost:27017/testing-project
JWT_SECRET=change_this_secret- Run the app
# development
npm run start
# watch mode
npm run start:dev
# production build
npm run build && npm run start:prod# build and start app + mongo
docker compose up --build
# stop
docker compose downThe compose file maps port 3000:3000 and starts a mongo:6 container on 27017 with a named volume.
start,start:dev,start:prodbuild,lint,formattest,test:watch,test:cov,test:e2e
Base URL: http://localhost:${PORT}/
-
Auth (
/auth)POST /auth/register— create account- body:
{ email: string, password: string }
- body:
POST /auth/login— returns{ access_token }- body:
{ email: string, password: string }
- body:
GET /auth/me— current user (requiresAuthorization: Bearer <token>)
-
Users (
/user)POST /user— create user- body:
{ name: string, age: number, tags?: string[] }
- body:
GET /user— list usersGET /user/:id— get user by idPATCH /user/:id— update user (partial)DELETE /user/:id— delete user
-
Auth
email: stringpassword: string(bcrypt-hashed)
-
User
name: stringage: numbertags?: string[]
- Configure
JWT_SECRETvia environment variables in production. The code currently includes'123'inJwtStrategyand inAuthService.sign(...). For production, align both to useprocess.env.JWT_SECRET. - Never commit real secrets to version control.
- Global
ValidationPipeis enabled inmain.ts. - DTOs enforce types:
CreateUserDtoforauthandusermodules.
src/
app.module.ts
main.ts
auth/
auth.controller.ts
auth.service.ts
auth.module.ts
dto/create-user.dto.ts
jwt-auth.guard.ts
jwt.strategy.ts
schema/auth.schema.ts
user/
user.controller.ts
user.service.ts
user.module.ts
dto/{create-user.dto.ts, update-user.dto.ts}
schema/user.schema.ts
# unit tests
npm run test
# e2e tests
npm run test:e2e
# coverage
npm run test:cov- PORT: App port (default 3000)
- MONGO_URI: Mongo connection string
- JWT_SECRET: JWT signing secret