A production-ready Express.js security template featuring HTTPS, JWT authentication, RBAC authorization, Helmet with custom CSP, rate limiting, and centralized error handling.
This project demonstrates how to implement layered API security using modern backend best practices.
- π HTTPS (TLS encryption)
- πͺ Helmet with custom Content Security Policy (CSP)
- π CORS configuration
- π¦ Rate limiting (IP-based)
- π JWT Authentication
- π Role-Based Access Control (RBAC)
- π§± Global Error Handling Middleware
- β Modular project structure
- π¦ Environment-based configuration
- Node.js
- Express.js
- Helmet
- CORS
- express-rate-limit
- jsonwebtoken
- bcryptjs
- node-forge (for self-signed HTTPS)
secure-express-api
β
βββ src
β βββ app.js
β βββ config.js
β βββ middleware
β β βββ auth.js
β β βββ error.middleware.js
β βββ routes
β β βββ auth.routes.js
β βββ utils
β βββ asyncHandler.js
β
βββ package.json
βββ README.md
The server runs over HTTPS using a self-signed certificate for development.
β Browsers will show a certificate warning in development. This is expected.
- Content Security Policy (CSP)
- X-Frame-Options
- HSTS
- X-Content-Type-Options
- Referrer Policy
Restricts allowed origins via environment configuration.
Limits excessive requests per IP to prevent abuse and brute-force attempts.
- Secure login endpoint
- Token expiration
- Protected routes
- Token verification middleware
- Role embedded inside JWT
- Admin-only route protection
- Global error middleware
- Async wrapper for promise-based routes
- Clean JSON error responses
Clone the repository:
git clone https://github.com/nick2726/secure_express_api.git
cd secure_express_apiInstall dependencies:
npm installCreate a .env file in the root:
PORT=3000
JWT_SECRET=your_super_secret_key
JWT_EXPIRES_IN=1h
CLIENT_URL=https://localhost:3000
RATE_LIMIT_WINDOW=15
RATE_LIMIT_MAX=100npm run devServer will run at:
https://localhost:3000
GET /
Response:
{
"success": true,
"message": "Secure Express Server Running π"
}POST /api/auth/login
Body:
{
"email": "admin@test.com",
"password": "password123"
}Returns:
{
"success": true,
"token": "JWT_TOKEN"
}GET /api/protected
Header:
Authorization: Bearer <token>
GET /api/admin
Requires:
- Valid JWT
- role = admin
- Request validation (Zod / Joi)
- Structured logging (Pino)
- Refresh token system
- Per-user rate limiting
- CSRF protection
- Production SSL via reverse proxy
This project follows:
- Layered security approach
- Middleware-driven architecture
- Separation of concerns
- Environment-based configuration
- Production-style error handling
MIT License
Pull requests are welcome.
If youβd like to enhance the security layer or improve architecture, feel free to fork and submit a PR.
Give the repository a star!
Client β HTTPS (TLS) β Express App βββ Helmet (CSP, Security Headers) βββ CORS βββ Rate Limiter βββ Routes β βββ Auth Routes β βββ Protected Routes β βββ Admin Routes (RBAC) βββ Global Error Handler