Skip to content

abdulvahabaa/Node-Mongoose-JWT-APIs-TS

Repository files navigation

Node.js REST API with TypeScript, Redis & Docker

Production-grade REST API built with Node.js, TypeScript, Express, MongoDB, and Redis.

πŸš€ Features

  • TypeScript - Type-safe development
  • Express.js - Fast, unopinionated web framework
  • MongoDB - NoSQL database with Mongoose ODM
  • Redis - In-memory caching and session management
  • Docker - Containerized deployment
  • JWT Authentication - Secure token-based auth
  • Rate Limiting - Redis-based distributed rate limiting
  • Security - Helmet, CORS, input validation
  • Logging - Morgan for HTTP request logging

πŸ“‹ Prerequisites

  • Node.js >= 18.0.0
  • Docker & Docker Compose
  • npm >= 9.0.0

πŸ› οΈ Installation

1. Clone the repository

git clone <your-repo-url>
cd node-rest-api-typescript

2. Install dependencies

npm install

3. Environment Setup

cp .env.example .env

Edit .env with your configuration:

# Application
NODE_ENV=development
PORT=3000

# Database
MONGODB_URI=mongodb://admin:password123@mongodb:27017/myapp?authSource=admin
MONGO_USERNAME=admin
MONGO_PASSWORD=password123

# Redis
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_PASSWORD=redis_secret_password

# JWT
JWT_SECRET=your-super-secret-jwt-key-change-in-production
JWT_EXPIRE=7d

🐳 Docker Setup

Development Mode

# Start all services (MongoDB, Redis, App, Admin UIs)
npm run docker:dev

# Or manually
docker-compose -f docker-compose.dev.yml up -d

# View logs
npm run docker:logs

Services available:

Production Mode

# Build production image
npm run docker:build

# Start production services
npm run docker:prod

# Stop services
npm run docker:down

πŸ’» Local Development (Without Docker)

1. Start MongoDB and Redis locally

# Using Homebrew (macOS)
brew install mongodb-community redis
brew services start mongodb-community
brew services start redis

# Or use Docker for just MongoDB and Redis
docker run -d -p 27017:27017 --name mongodb mongo:7.0
docker run -d -p 6379:6379 --name redis redis:7-alpine

2. Update .env for local development

MONGODB_URI=mongodb://localhost:27017/myapp
REDIS_HOST=localhost

3. Run the application

# Development mode with hot reload
npm run dev

# Build for production
npm run build

# Start production server
npm start

πŸ“ Project Structure

src/
β”œβ”€β”€ config/
β”‚   β”œβ”€β”€ db.ts              # MongoDB connection
β”‚   └── redis.ts           # Redis client & utilities
β”œβ”€β”€ middleware/
β”‚   β”œβ”€β”€ auth.middleware.ts
β”‚   β”œβ”€β”€ cache.middleware.ts
β”‚   β”œβ”€β”€ error.middleware.ts
β”‚   └── redisRateLimiter.middleware.ts
β”œβ”€β”€ models/
β”‚   └── user.model.ts
β”œβ”€β”€ routes/
β”‚   β”œβ”€β”€ auth.routes.ts
β”‚   └── user.routes.ts
β”œβ”€β”€ services/
β”‚   └── cache.service.ts   # Redis cache service
β”œβ”€β”€ types/
β”‚   └── express.d.ts
└── server.ts              # Application entry point

πŸ”‘ Redis Usage Examples

Caching

import { cacheService } from './services/cache.service';

// Cache user data
await cacheService.cacheUser(userId, userData, 3600);

// Get cached user
const user = await cacheService.getCachedUser(userId);

// Cache query results
await cacheService.cacheQuery('allUsers', users);

Rate Limiting

import { redisRateLimiter } from './middleware/redisRateLimiter.middleware';

// Custom rate limiter
app.use('/api/expensive', redisRateLimiter({
  windowMs: 60000,  // 1 minute
  max: 10,          // 10 requests per minute
}));

Session Management

// Create session
await cacheService.createSession(sessionId, userId, 86400);

// Get session
const session = await cacheService.getSession(sessionId);

// Delete session
await cacheService.deleteSession(sessionId);

πŸ”’ API Endpoints

Authentication

  • POST /api/auth/register - Register new user
  • POST /api/auth/login - Login user
  • POST /api/auth/logout - Logout user

Users

  • GET /api/users - Get all users (cached)
  • GET /api/users/:id - Get user by ID
  • PUT /api/users/:id - Update user
  • DELETE /api/users/:id - Delete user

Health Check

  • GET /health - Server health status

πŸ“Š Monitoring

Redis Commander

Access Redis GUI at http://localhost:8081

  • View all keys
  • Monitor memory usage
  • Execute Redis commands

Mongo Express

Access MongoDB GUI at http://localhost:8082

  • Browse collections
  • Run queries
  • Manage documents

πŸ§ͺ Testing

npm test

πŸ“ Scripts

npm run dev          # Development mode with hot reload
npm run build        # Build TypeScript to JavaScript
npm start            # Start production server
npm run lint         # Lint code
npm run lint:fix     # Fix linting errors
npm run format       # Format code with Prettier

# Docker scripts
npm run docker:dev   # Start development environment
npm run docker:prod  # Start production environment
npm run docker:down  # Stop all containers
npm run docker:logs  # View container logs
npm run docker:build # Build Docker images

🚒 Deployment

Docker Production Deployment

  1. Build the image:
docker build -t your-api:latest .
  1. Push to registry:
docker tag your-api:latest your-registry/your-api:latest
docker push your-registry/your-api:latest
  1. Deploy to server:
docker-compose -f docker-compose.yml up -d

Environment Variables for Production

Ensure these are set in production:

  • Generate strong JWT_SECRET
  • Use secure database passwords
  • Set NODE_ENV=production
  • Configure proper CORS_ORIGIN

πŸ” Security Features

  • βœ… Helmet.js for security headers
  • βœ… CORS configuration
  • βœ… Rate limiting with Redis
  • βœ… JWT token authentication
  • βœ… Password hashing with Argon2
  • βœ… Input validation with Joi
  • βœ… Token blacklisting for logout
  • βœ… Graceful shutdown handling

πŸ“š Technologies

  • Node.js - Runtime environment
  • TypeScript - Type safety
  • Express - Web framework
  • MongoDB - Database
  • Mongoose - ODM
  • Redis - Caching & sessions
  • Docker - Containerization
  • JWT - Authentication
  • Argon2 - Password hashing

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch
  3. Commit your changes
  4. Push to the branch
  5. Create a Pull Request

πŸ“„ License

MIT

πŸ‘¨β€πŸ’» Author

Your Name


Made with ❀️ and TypeScript

About

Production-grade REST API built with Node.js, TypeScript, Express, MongoDB, and Redis.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published