A comprehensive, production-ready REST API demonstrating industry best practices for building scalable, maintainable server applications.
This is a learning repository designed to teach you how to build production-ready REST APIs. Every concept is implemented with extensive documentation, code comments, and explanations.
- โ Input Validation - How to validate and sanitize all client input
- โ Concurrency Control - How to prevent race conditions and overselling
- โ Idempotency - How to handle duplicate requests safely
- โ Caching - How to improve performance with intelligent caching
- โ Structured Logging - How to debug production issues with tracing
- โ Security - How to protect against common vulnerabilities
- โ Error Handling - How to return consistent, helpful error messages
- โ API Design - How to design clean, intuitive REST APIs
- โ TypeScript - How to write type-safe Node.js applications
- โ Testing - How to validate your code works correctly
- Node.js >= 20.0.0
- npm >= 10.0.0
- Git (for cloning)
# Clone the repository git clone https://github.com/your-username/se-node-server-rest-apis.git cd se-node-server-rest-apis # Install dependencies npm install # Set up environment (optional - defaults work for development) cp .env.example .env # Run database migrations npm run db:migrate # Seed the database with sample data npm run db:seed # Start the development server npm run dev
The API will be available at http://localhost:3000
# Check health curl http://localhost:3000/health # List items curl http://localhost:3000/api/v1/items # Reserve an item curl -X POST http://localhost:3000/api/v1/reserve \ -H "Content-Type: application/json" \ -H "Idempotency-Key: test-key-123" \ -d '{"userId":"user_test","itemId":"item_1","qty":1}'
A modern Next.js 16 frontend with glass-morphism UI is included in the frontend/ directory.
| Component | Technology |
|---|---|
| Framework | Next.js 16 (App Router) |
| Language | TypeScript 5 |
| Styling | Tailwind CSS 4 |
| UI Library | shadcn/ui |
| State | TanStack Query |
| Forms | React Hook Form + Zod |
# Navigate to frontend directory cd frontend # Install dependencies npm install # Set up environment cp .env.example .env.local # Start development server (runs on port 3001) npm run dev
The frontend will be available at http://localhost:3001
- โ Glass-morphism Design - Modern translucent UI with backdrop blur
- โ Real-time Updates - TanStack Query for live data synchronization
- โ Form Validation - Zod schemas matching backend validation
- โ Idempotency - Automatic Idempotency-Key header generation
- โ Error Handling - Request ID display for debugging
- โ Responsive - Mobile-first design
๐ frontend/README.md - Complete frontend documentation
We've created comprehensive learning documentation in the docs/ directory:
- docs/01-introduction.md - Overview and architecture
- docs/02-validation.md - Input validation with Zod
- docs/03-concurrency.md - Atomic database operations
- docs/04-idempotency.md - Handling duplicate requests
- docs/05-caching.md - Performance with caching
- docs/06-logging.md - Observability and tracing
- docs/07-validation-guide.md - Complete testing guide
๐ก Start with docs/README.md for the full learning guide.
- POSTMAN_GUIDE.md - Complete Postman testing instructions
- LEARNING_CHECKLIST.md - Track your learning progress
Ready-to-use Postman collection for testing all features:
- postman-collection.json - Import this into Postman
- postman-environment.json - Environment variables
| Component | Technology | Why? |
|---|---|---|
| Runtime | Node.js 20+ | Latest LTS, ES2022 support |
| Framework | Express 4.x | Battle-tested, huge ecosystem |
| Language | TypeScript 5.x | Type safety, better DX |
| Database | SQLite (better-sqlite3) | Embedded, fast, zero-config |
| Validation | Zod | Runtime + compile-time validation |
| Logging | Pino | Ultra-fast structured logging |
| Security | Helmet, CORS | Security headers, cross-origin |
| Component | Technology | Why? |
|---|---|---|
| Framework | Next.js 16 | React 19, App Router, Turbopack |
| Styling | Tailwind CSS 4 | Utility-first, JIT compiler |
| UI Components | shadcn/ui | Accessible, customizable |
| State Management | TanStack Query | Server state, caching |
| Forms | React Hook Form | Performance, flexibility |
| Validation | Zod | Type-safe schema validation |
se-node-server-rest-apis/
โโโ docs/ # Learning documentation
โ โโโ README.md # Documentation index
โ โโโ 01-introduction.md # Overview
โ โโโ 02-validation.md # Input validation
โ โโโ 03-concurrency.md # Race conditions
โ โโโ 04-idempotency.md # Duplicate requests
โ โโโ 05-caching.md # Performance
โ โโโ 06-logging.md # Observability
โ โโโ 07-validation-guide.md # Complete testing guide
โ
โโโ src/ # Source code
โ โโโ cache/ # Caching layer
โ โ โโโ index.ts # TTL cache with invalidation
โ โ โโโ README.md # Module learning guide
โ โโโ config/ # Configuration
โ โ โโโ index.ts # Environment variables
โ โ โโโ README.md # Module learning guide
โ โโโ database/ # Database layer
โ โ โโโ index.ts # SQLite connection
โ โ โโโ migrate.ts # Migration runner
โ โ โโโ seed.ts # Data seeding
โ โ โโโ README.md # Module learning guide
โ โโโ http/ # Response utilities
โ โ โโโ index.ts # ok(), fail() helpers
โ โ โโโ README.md # Module learning guide
โ โโโ idempotency/ # Idempotency handling
โ โ โโโ index.ts # Duplicate request prevention
โ โ โโโ README.md # Module learning guide
โ โโโ middleware/ # Express middleware
โ โ โโโ rateLimit.ts # Token bucket rate limiting
โ โ โโโ security.ts # Security headers, CORS
โ โ โโโ README.md # Module learning guide
โ โโโ observability/ # Logging & metrics
โ โ โโโ index.ts # Pino structured logging
โ โ โโโ README.md # Module learning guide
โ โโโ routes/ # API endpoints
โ โ โโโ index.ts # Main routes
โ โ โโโ health.ts # Health checks
โ โ โโโ README.md # Module learning guide
โ โโโ services/ # Business logic
โ โ โโโ reservations.ts # Domain logic
โ โ โโโ README.md # Module learning guide
โ โโโ types/ # TypeScript types
โ โ โโโ index.ts # All type definitions
โ โ โโโ README.md # Module learning guide
โ โโโ validation/ # Zod schemas
โ โ โโโ schemas.ts # Request/response schemas
โ โ โโโ README.md # Module learning guide
โ โโโ server.ts # Application entry point
โ
โโโ frontend/ # Next.js 16 Frontend Application
โ โโโ src/ # Frontend source
โ โ โโโ app/ # Next.js App Router
โ โ โโโ components/ # React components
โ โ โ โโโ layout/ # Layout components
โ โ โ โโโ ui/ # shadcn/ui components
โ โ โ โโโ ui-blocks/ # Custom UI blocks
โ โ โโโ lib/ # Utilities
โ โ โโโ api/ # API client
โ โ โโโ query/ # TanStack Query
โ โโโ .env.example # Frontend env template
โ โโโ package.json
โ โโโ README.md # Frontend documentation
โ
โโโ postman-collection.json # Postman collection (import this!)
โโโ postman-environment.json # Postman environment (import this!)
โโโ POSTMAN_GUIDE.md # Complete Postman instructions
โโโ LEARNING_CHECKLIST.md # Track your progress
โโโ POSTMAN_COLLECTION.md # API testing with curl
โ
โโโ .env.example # Environment template
โโโ package.json # Dependencies
โโโ tsconfig.json # TypeScript config
โโโ README.md # This file
Problem: Clients send invalid or malicious data.
Solution: Validate all input at the API boundary using Zod schemas.
// src/validation/schemas.ts export const reserveRequestSchema = z.object({ userId: z.string().min(1), itemId: z.string().regex(/^item_\d+$/), qty: z.number().int().min(1).max(5) });
Learn more: docs/02-validation.md
Problem: Two users reserve the last item simultaneously, both succeed (overselling).
Solution: Atomic database operations with conditional updates.
UPDATE items SET availableQty = availableQty - ? WHERE id = ? AND availableQty >= ?
Learn more: docs/03-concurrency.md
Problem: Network retries create duplicate reservations.
Solution: Store responses by unique key, replay on duplicates.
// First request: Process and store // Second request: Return cached response
Learn more: docs/04-idempotency.md
Problem: Repeated database queries waste resources.
Solution: Cache responses with TTL, invalidate on changes.
const cached = getCache('items'); if (cached) return cached; const items = fetchItems(); setCache('items', items, 30_000);
Learn more: docs/05-caching.md
Problem: Debugging production issues is hard without context.
Solution: Structured logs with request tracing.
{
"level": "info",
"requestId": "abc-123",
"msg": "Item reserved",
"userId": "user_1",
"itemId": "item_1"
}Learn more: docs/06-logging.md
http://localhost:3000/api/v1
| Method | Endpoint | Description |
|---|---|---|
| GET | /items |
List all items |
| GET | /items/:id |
Get single item |
| POST | /reserve |
Reserve an item |
| POST | /confirm |
Confirm reservation |
| POST | /cancel |
Cancel reservation |
| GET | /reservations/user/:userId |
List user's reservations |
| GET | /health |
Health check |
All responses follow a consistent format:
Success:
{
"ok": true,
"data": { ... }
}Error:
{
"ok": false,
"error": {
"code": "ERROR_CODE",
"message": "Description",
"details": { ... },
"requestId": "uuid"
}
}Complete testing setup ready to use:
- Import
postman-collection.jsoninto Postman - Import
postman-environment.jsoninto Postman - Select "Reservation API - Local" environment
- Start testing!
๐ Full instructions: POSTMAN_GUIDE.md
# Health check curl http://localhost:3000/health # List items curl http://localhost:3000/api/v1/items # Reserve an item curl -X POST http://localhost:3000/api/v1/reserve \ -H "Content-Type: application/json" \ -H "Idempotency-Key: test-key-123" \ -d '{"userId":"user_test","itemId":"item_1","qty":1}' # Confirm reservation curl -X POST http://localhost:3000/api/v1/confirm \ -H "Content-Type: application/json" \ -d '{"userId":"user_test","reservationId":"res_abc123"}'
๐ More examples: POSTMAN_COLLECTION.md
Track your learning progress and validate each feature:
๐ Checklist: LEARNING_CHECKLIST.md
npm run dev # Start development server with hot reload npm run build # Compile TypeScript npm run start # Start production server npm run lint # Lint code npm run format # Format code npm run db:migrate # Run database migrations npm run db:seed # Seed database npm run clean # Clean build output
# .env file (copy from .env.example)
NODE_ENV=development
PORT=3000
LOG_LEVEL=debug
DB_PATH=./app.db- Input Validation with Zod schemas
- Atomic Operations to prevent race conditions
- Idempotency for safe request retries
- Response Caching with automatic invalidation
- Rate Limiting (token bucket algorithm)
- Structured Logging with request tracing
- Security Headers (Helmet.js)
- CORS Configuration
- Health Check Endpoints
- Graceful Shutdown
- TypeScript (100% typed)
- Database Migrations
- Consistent Error Responses
We've built a reservation system for an inventory store because it demonstrates:
- Time-sensitive operations - Reservations expire after 10 minutes
- State transitions - reserved โ confirmed โ cancelled/expired
- Concurrency - Multiple users competing for limited inventory
- Idempotency needs - Network retries can cause double-charging
- Background jobs - Automatic expiration with stock restoration (30s interval)
Request โ Security Middleware โ Rate Limiting โ Validation โ Route Handler
โ
Business Logic
โ
Database (SQLite)
โ
(Cache/Idempotency)
โ
Response
docs/README.md- Complete learning guide- Each source file has extensive comments
- Type definitions in
src/types/index.tsfor reference
This is a learning repository. Feel free to:
- Explore the code
- Make changes and break things
- Fix issues and learn from them
- Add new features
MIT License - See LICENSE file for details
Ready to dive in? Continue to the learning documentation:
โ Start Learning with docs/01-introduction.md
Or jump straight to a topic:
๐ก Tip: Every file in this repository is heavily documented. Start exploring and happy learning!