Skip to content

Repository files navigation

πŸ” Session Auth - Express.js Authentication Boilerplate

Node.js Version Express.js Version License Code Style Linting PRs Welcome

πŸ“š Educational project for learning authentication patterns with Express.js, sessions, and CSRF protection.

An authentication system built with Express.js, featuring session-based authentication, CSRF protection, rate limiting, comprehensive logging, and extensive testing. Perfect for learning modern web authentication patterns.

Run Tests

πŸ”„ Looking for a token-based alternative? Check out: https://github.com/n1kFord/jwt-auth

✨ Features

  • πŸ”‘ Session-based authentication with express-session
  • πŸ›‘οΈ CSRF protection (Synchronizer Token Pattern)
  • πŸ“¦ Redis session store for production scalability
  • πŸ—„οΈ MongoDB with Mongoose ODM
  • πŸ“ Winston + Morgan logging with chalk styling
  • πŸ§ͺ Comprehensive test suite with Jest & Supertest
  • ✨ ESLint + Prettier for code quality
  • 🚦 Rate limiting to prevent brute force attacks
  • πŸ” Password hashing with bcrypt
  • πŸ›‘οΈ CORS configuration for cross-origin requests
  • πŸ“ Input validation with express-validator
  • πŸ”„ Session regeneration on login (prevents fixation attacks)

πŸ› οΈ Tech Stack

  • Runtime: Node.js 20+
  • Framework: Express.js 5.x
  • Database: MongoDB + Mongoose
  • Session Store: Redis (connect-redis)
  • Logging: Winston, Morgan, Chalk
  • Testing: Jest + Supertest
  • Code Quality: ESLint + Prettier
  • Security: bcrypt, CSRF, rate limiting, CORS

πŸš€ Quick Start

Prerequisites

  • Docker & Docker Compose (recommended)
  • Node.js >= 20 (for local development)
  • npm or yarn

With Docker (Recommended)

# Clone repository
git clone https://github.com/n1kFord/session-auth.git
cd session-auth

# Start all services (MongoDB, Redis, and API)
docker compose up -d

# Check logs
docker compose logs -f

# Stop services
docker compose down

# Stop and remove volumes (clears database)
docker compose down -v

Local Development

# Install dependencies
npm install

# Setup environment
cp .env.example .env
# Edit .env with your configuration

# Start MongoDB and Redis (using Docker)
docker compose up -d mongo redis

# Start development server
npm run dev

# Production mode
npm start

Environment Variables

# Server
PORT=8080
NODE_ENV=development

# MongoDB
MONGO_URI=mongodb://localhost:27017/authDB

# Redis
REDIS_CLIENT_URI=redis://localhost:6379

# Redis Secret
REDIS_SECRET=your_super_secret_redis_key_min_32_chars

πŸ“ Project Structure

session-auth/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config/          # DB, Redis, session config
β”‚   β”œβ”€β”€ middlewares/     # Auth, CSRF, validation, logging
β”‚   β”œβ”€β”€ models/          # User model
β”‚   β”œβ”€β”€ routers/         # /auth and /me endpoints
β”‚   β”œβ”€β”€ utils/           # Helpers (csrf, hash, session)
β”‚   β”œβ”€β”€ __tests__/       # Jest tests
β”‚   └── index.js         # Entry point
β”œβ”€β”€ logs/                # Winston log files
β”œβ”€β”€ docker-compose.yml
β”œβ”€β”€ Dockerfile
└── package.json

πŸ“ Logging System

  • Winston β€” file + console logging with levels (error, warn, info, debug)
  • Morgan β€” HTTP request logging integrated with Winston
  • Chalk β€” colored console output for better readability

🎨 Code Style

npm run lint        # Check code style
npm run format      # Auto-format with Prettier

πŸ”Œ API Endpoints

Authentication (/auth)

Method Endpoint Description CSRF
POST /register Register user ❌
POST /login Login user ❌
POST /logout Logout user ❌

User Management (/me)

Method Endpoint Description CSRF
GET / Get profile ❌
POST /change-email Change email βœ…
POST /change-password Change password βœ…
POST /change-username Change username βœ…
POST /change-bio Change bio βœ…
DELETE / Delete account βœ…

πŸ“ Examples

# Register
curl -X POST http://localhost:8080/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"secret123","confirmPassword":"secret123"}'

# Login
curl -X POST http://localhost:8080/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"secret123"}'

# Get profile (with CSRF)
curl -X GET http://localhost:8080/me/ \
  -H "X-XSRF-Token: your-csrf-token" \
  -H "Cookie: sessionId=your-session-id"

πŸ§ͺ Testing

npm test

🐳 Docker

# Start all services
docker-compose up -d

# Stop all services
docker-compose down

πŸ›‘οΈ Security

  • Session-based with HTTP-only cookies
  • CSRF protection (Synchronizer Token Pattern)
  • Rate limiting β€” 100 req/15min, 10 login attempts
  • Password hashing with bcrypt
  • Session regeneration on login
  • Input validation with express-validator

πŸ“„ License

This project is licensed under the MIT License.
Feel free to use, modify, and distribute with attribution.

πŸ’‘ Created with care by @n1kFord


⭐ Star this repo if you found it helpful!

About

πŸ” Authentication boilerplate with Express.js, sessions, CSRF protection, and Redis

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages