An opinionated, production-ready Express.js template that demonstrates best practices for building secure, observable, and testable REST APIs. It includes layered architecture, authentication with JWT and refresh tokens, request validation, MongoDB integration, API documentation, and developer tooling.
- Modular architecture separating configuration, routes, controllers, services, and data access layers.
- Secure by default middleware stack with Helmet, rate limiting, request sanitization, and CORS controls.
- JWT authentication with refresh tokens, role-based authorization, and reusable access control helpers.
- Centralised error handling using custom
ApiErrorobjects and environment-aware responses. - Comprehensive logging powered by Winston and HTTP request tracing via Morgan.
- API documentation automatically generated with Swagger UI (
/docs). - Test harness with Jest and SuperTest for integration testing and continuous integration readiness.
- Environment validation via Joi to prevent misconfiguration at boot time.
- Modern web experience including secured sessions, CSRF protection, and a responsive EJS dashboard.
βββ src
β βββ app.js # Express app configuration
β βββ server.js # Application bootstrap & graceful shutdown
β βββ config/ # Environment, logger, database, roles, token settings
β βββ controllers/ # Request handlers (REST, auth, health, web views)
β βββ docs/ # Swagger configuration & definitions
β βββ middlewares/ # Auth, validation, error & logging middleware
β βββ models/ # Mongoose schemas (User, Token)
β βββ routes/v1/ # Versioned REST API routes
β βββ routes/web/ # Browser routes with CSRF/session handling
β βββ services/ # Business logic & orchestration layer
β βββ views/ # EJS templates for UI & error pages
β βββ public/ # Static assets (CSS/JS) served via /assets
β βββ utils/ # Shared helpers (ApiError, password hashing, etc.)
β βββ validations/ # Joi schemas & custom validators
βββ src/tests/ # Jest setup and sample integration tests
βββ example.env # Documented environment variables
βββ jest.config.js # Jest configuration
- Clone and install dependencies
git clone <repository-url> cd ExpressJS-Template npm install
- Configure environment variables
- Copy
example.envto.envand adapt values to your setup. - Mandatory values include MongoDB connection details and a strong
JWT_SECRET.
- Copy
- Run the API locally
The server listens on
npm run dev
http://localhost:8080by default and exposes interactive docs athttp://localhost:8080/docs.
| Name | Description | Default |
|---|---|---|
NODE_ENV |
Node runtime mode (development, production, test) |
development |
PORT |
HTTP port | 8080 |
MONGODB_URI |
MongoDB connection string | mongodb://127.0.0.1:27017/expressjs_template |
MONGODB_DB_NAME |
MongoDB database name | expressjs_template |
JWT_SECRET |
Secret used to sign JWT tokens | required in production |
JWT_ACCESS_EXPIRATION_MINUTES |
Access token lifetime in minutes | 30 |
JWT_REFRESH_EXPIRATION_DAYS |
Refresh token lifetime in days | 30 |
LOG_LEVEL |
Winston log level | info |
CORS_ORIGIN |
Comma separated list of allowed origins or * |
* |
SESSION_SECRET |
Secret used to sign & encrypt session data | required in production |
SESSION_NAME |
Name of the session cookie | sid |
SESSION_IDLE_TIMEOUT_MINUTES |
Session idle timeout before invalidation | 30 |
SESSION_COOKIE_SECURE |
Enable secure cookies (requires HTTPS/proxy) | false |
TRUST_PROXY |
Trust reverse proxy headers for secure cookies | false |
| Command | Description |
|---|---|
npm run dev |
Start API & web UI with nodemon and auto-reload on file changes. |
npm start |
Launch the API and web interface in production mode. |
npm test |
Execute Jest test suite (runs in NODE_ENV=test). |
GET /liefert eine gehΓ€rtete Landing Page mit ProjektΓΌberblick und Schnellzugriffen.- Authentifizierung & Registrierung erfolgen ΓΌber EJS-Formulare mit CSRF-Tokens und verschlΓΌsselten Sessions.
- Das Dashboard zeigt Nutzerprofil, aktive Tokens und empfohlene nΓ€chste Schritte fΓΌr Deployments.
- Fehler fΓΌr Browser-Clients werden als stilisierte HTML-Seiten ausgegeben, wΓ€hrend die API weiterhin JSON liefert.
- Users register via
POST /v1/auth/register. Passwords are hashed with Node.jscrypto.scryptbefore persisting. - Login with
POST /v1/auth/loginto receive access and refresh tokens. - Refresh access tokens through
POST /v1/auth/refresh-tokens. - Revoke refresh tokens using
POST /v1/auth/logout. - Protect endpoints by attaching
Authorization: Bearer <accessToken>headers. - Role-based permissions are defined in
src/config/roles.jsand enforced via theauthmiddleware. - Browser sessions are encrypted in MongoDB, regenerated on login, and protected via CSRF tokens for every form submit.
Swagger documentation is available at /docs (disabled during tests). The generated specification can be reused for client generation or platform integration.
Key endpoints:
GET /healthβ Lightweight service health probe.POST /v1/auth/registerβ Create a new account.POST /v1/auth/loginβ Exchange credentials for JWT tokens.POST /v1/auth/refresh-tokensβ Renew expired access tokens.GET /v1/users/profileβ Retrieve the authenticated user's profile.GET /v1/usersβ Admin-only paginated listing of users.GET /β Landing page, documentation hub, and entry into the secured dashboard.
- Jest runs in isolated
NODE_ENV=testmode with deterministic environment setup (src/tests/jest.setup.js). - Example integration test (
src/tests/integration/health.test.js) demonstrates how to exercise routes with SuperTest. - Extend the suite with further unit or integration tests as new features are introduced.
- Winston logger centralises structured logging across the application.
- Morgan HTTP logging middleware writes concise request traces.
- Custom
ApiErrorensures consistent error payloads and stack traces during development. - Health check endpoint simplifies infrastructure liveness and readiness probes.
- Browser requests receive branded HTML error pages while API consumers continue to receive JSON payloads.
- Add new modules under
src/servicesto encapsulate domain logic. - Create DTOs/validators in
src/validationsand pair them with routes via thevalidatemiddleware. - Use
src/utilsfor sharable helpers (e.g., mailers, external integrations). - Update Swagger definitions in
src/docs/swaggerDef.jsas you add endpoints. - Expand the web experience inside
src/routes/webandsrc/viewsfor custom flows such as onboarding, billing, or admin dashboards.
Released under the MIT License.
Built with β€οΈ to jump-start enterprise-grade Express.js services.