Skip to content

Commit 4dfa198

Browse files
authored
New Version -> 1.0.1 -> Enterprise Level Reached
feat: add secured web experience and session hardening
2 parents 427a824 + 4229e8b commit 4dfa198

File tree

105 files changed

+2622
-3926
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

105 files changed

+2622
-3926
lines changed

README.md

Lines changed: 132 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,143 @@
1-
# Express.js Template Repository
1+
# Express Enterprise Starter
22

3-
This repository provides a basic template for developing web applications with Express.js. It offers a solid foundation and a pre-made folder structure to accelerate development.
3+
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.
44

5-
## Features
5+
## ✨ Highlights
66

7-
- **Pre-made Folder Structure**: Clear separation of routes, middleware, services, and other modules for improved organization.
8-
- **Basic Middleware**: Includes essential middleware like Body-Parser and CORS for smooth application development.
9-
- **Easy Configuration**: Simple setup of server and database connections for quick deployment.
10-
- **RESTful Routes**: Pre-defined routes for common RESTful operations such as GET, POST, PUT, and DELETE.
11-
- **Error Handling**: Basic error handling and middleware to enhance application robustness.
12-
- **Documentation**: README.md with instructions for using and extending the template.
7+
- **Modular architecture** separating configuration, routes, controllers, services, and data access layers.
8+
- **Secure by default** middleware stack with Helmet, rate limiting, request sanitization, and CORS controls.
9+
- **JWT authentication** with refresh tokens, role-based authorization, and reusable access control helpers.
10+
- **Centralised error handling** using custom `ApiError` objects and environment-aware responses.
11+
- **Comprehensive logging** powered by Winston and HTTP request tracing via Morgan.
12+
- **API documentation** automatically generated with Swagger UI (`/docs`).
13+
- **Test harness** with Jest and SuperTest for integration testing and continuous integration readiness.
14+
- **Environment validation** via Joi to prevent misconfiguration at boot time.
15+
- **Modern web experience** including secured sessions, CSRF protection, and a responsive EJS dashboard.
1316

14-
## Installation
17+
## 🗂️ Project Structure
1518

16-
1. Clone this repository to your local machine.
17-
2. Navigate to the template directory and install dependencies with `npm install`.
18-
3. Customize configuration files to suit your application.
19-
4. Start the application with `npm start`.
19+
```
20+
├── src
21+
│ ├── app.js # Express app configuration
22+
│ ├── server.js # Application bootstrap & graceful shutdown
23+
│ ├── config/ # Environment, logger, database, roles, token settings
24+
│ ├── controllers/ # Request handlers (REST, auth, health, web views)
25+
│ ├── docs/ # Swagger configuration & definitions
26+
│ ├── middlewares/ # Auth, validation, error & logging middleware
27+
│ ├── models/ # Mongoose schemas (User, Token)
28+
│ ├── routes/v1/ # Versioned REST API routes
29+
│ ├── routes/web/ # Browser routes with CSRF/session handling
30+
│ ├── services/ # Business logic & orchestration layer
31+
│ ├── views/ # EJS templates for UI & error pages
32+
│ ├── public/ # Static assets (CSS/JS) served via /assets
33+
│ ├── utils/ # Shared helpers (ApiError, password hashing, etc.)
34+
│ └── validations/ # Joi schemas & custom validators
35+
├── src/tests/ # Jest setup and sample integration tests
36+
├── example.env # Documented environment variables
37+
└── jest.config.js # Jest configuration
38+
```
2039

21-
## Usage
40+
## 🚀 Getting Started
2241

23-
- Add new routes and middleware in the respective folders.
24-
- Configure your database connection in the `.env` file.
25-
- Adjust server configuration in the `.env` file.
26-
- Add additional middleware or services to extend your application.
42+
1. **Clone and install dependencies**
43+
```bash
44+
git clone <repository-url>
45+
cd ExpressJS-Template
46+
npm install
47+
```
48+
2. **Configure environment variables**
49+
- Copy `example.env` to `.env` and adapt values to your setup.
50+
- Mandatory values include MongoDB connection details and a strong `JWT_SECRET`.
51+
3. **Run the API locally**
52+
```bash
53+
npm run dev
54+
```
55+
The server listens on `http://localhost:8080` by default and exposes interactive docs at `http://localhost:8080/docs`.
2756

28-
## Contributors
57+
## 🔧 Environment Variables
2958

30-
- [Tim Hauke](https://hauknetz.de) - Lead Developer
59+
| Name | Description | Default |
60+
| ---- | ----------- | ------- |
61+
| `NODE_ENV` | Node runtime mode (`development`, `production`, `test`) | `development` |
62+
| `PORT` | HTTP port | `8080` |
63+
| `MONGODB_URI` | MongoDB connection string | `mongodb://127.0.0.1:27017/expressjs_template` |
64+
| `MONGODB_DB_NAME` | MongoDB database name | `expressjs_template` |
65+
| `JWT_SECRET` | Secret used to sign JWT tokens | _required in production_ |
66+
| `JWT_ACCESS_EXPIRATION_MINUTES` | Access token lifetime in minutes | `30` |
67+
| `JWT_REFRESH_EXPIRATION_DAYS` | Refresh token lifetime in days | `30` |
68+
| `LOG_LEVEL` | Winston log level | `info` |
69+
| `CORS_ORIGIN` | Comma separated list of allowed origins or `*` | `*` |
70+
| `SESSION_SECRET` | Secret used to sign & encrypt session data | _required in production_ |
71+
| `SESSION_NAME` | Name of the session cookie | `sid` |
72+
| `SESSION_IDLE_TIMEOUT_MINUTES` | Session idle timeout before invalidation | `30` |
73+
| `SESSION_COOKIE_SECURE` | Enable secure cookies (requires HTTPS/proxy) | `false` |
74+
| `TRUST_PROXY` | Trust reverse proxy headers for secure cookies | `false` |
3175

32-
## License
76+
## 📚 Available Scripts
3377

34-
This project is licensed under the [MIT License](Link to License).
78+
| Command | Description |
79+
| ------------------ | ------------------------------------------------------------- |
80+
| `npm run dev` | Start API & web UI with `nodemon` and auto-reload on file changes. |
81+
| `npm start` | Launch the API and web interface in production mode. |
82+
| `npm test` | Execute Jest test suite (runs in `NODE_ENV=test`). |
83+
84+
## 🖥️ Web Experience
85+
86+
- `GET /` liefert eine gehärtete Landing Page mit Projektüberblick und Schnellzugriffen.
87+
- Authentifizierung & Registrierung erfolgen über EJS-Formulare mit CSRF-Tokens und verschlüsselten Sessions.
88+
- Das Dashboard zeigt Nutzerprofil, aktive Tokens und empfohlene nächste Schritte für Deployments.
89+
- Fehler für Browser-Clients werden als stilisierte HTML-Seiten ausgegeben, während die API weiterhin JSON liefert.
90+
91+
## 🔐 Authentication & Authorization
92+
93+
- Users register via `POST /v1/auth/register`. Passwords are hashed with Node.js `crypto.scrypt` before persisting.
94+
- Login with `POST /v1/auth/login` to receive access and refresh tokens.
95+
- Refresh access tokens through `POST /v1/auth/refresh-tokens`.
96+
- Revoke refresh tokens using `POST /v1/auth/logout`.
97+
- Protect endpoints by attaching `Authorization: Bearer <accessToken>` headers.
98+
- Role-based permissions are defined in `src/config/roles.js` and enforced via the `auth` middleware.
99+
- Browser sessions are encrypted in MongoDB, regenerated on login, and protected via CSRF tokens for every form submit.
100+
101+
## 📘 API Reference
102+
103+
Swagger documentation is available at `/docs` (disabled during tests). The generated specification can be reused for client generation or platform integration.
104+
105+
Key endpoints:
106+
107+
- `GET /health` – Lightweight service health probe.
108+
- `POST /v1/auth/register` – Create a new account.
109+
- `POST /v1/auth/login` – Exchange credentials for JWT tokens.
110+
- `POST /v1/auth/refresh-tokens` – Renew expired access tokens.
111+
- `GET /v1/users/profile` – Retrieve the authenticated user's profile.
112+
- `GET /v1/users` – Admin-only paginated listing of users.
113+
- `GET /` – Landing page, documentation hub, and entry into the secured dashboard.
114+
115+
## 🧪 Testing Strategy
116+
117+
- Jest runs in isolated `NODE_ENV=test` mode with deterministic environment setup (`src/tests/jest.setup.js`).
118+
- Example integration test (`src/tests/integration/health.test.js`) demonstrates how to exercise routes with SuperTest.
119+
- Extend the suite with further unit or integration tests as new features are introduced.
120+
121+
## 📈 Observability & Error Handling
122+
123+
- Winston logger centralises structured logging across the application.
124+
- Morgan HTTP logging middleware writes concise request traces.
125+
- Custom `ApiError` ensures consistent error payloads and stack traces during development.
126+
- Health check endpoint simplifies infrastructure liveness and readiness probes.
127+
- Browser requests receive branded HTML error pages while API consumers continue to receive JSON payloads.
128+
129+
## 🛠️ Extending the Template
130+
131+
- Add new modules under `src/services` to encapsulate domain logic.
132+
- Create DTOs/validators in `src/validations` and pair them with routes via the `validate` middleware.
133+
- Use `src/utils` for sharable helpers (e.g., mailers, external integrations).
134+
- Update Swagger definitions in `src/docs/swaggerDef.js` as you add endpoints.
135+
- Expand the web experience inside `src/routes/web` and `src/views` for custom flows such as onboarding, billing, or admin dashboards.
136+
137+
## 🪪 License
138+
139+
Released under the [MIT License](./LICENSE).
140+
141+
---
142+
143+
Built with ❤️ to jump-start enterprise-grade Express.js services.

Samples/basic-routes.txt

Lines changed: 0 additions & 16 deletions
This file was deleted.

example.env

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
1-
# Base Settings
2-
APP_NAME=API-Template #The name of the application.
3-
BASE_URL= #The Domain you have as url.
4-
COMPANY= #The company name of your company.
5-
PORT= #Port of the Node.js application.
6-
7-
# Database
8-
DATABASE_TYPE= #mysql / mongodb #Database Type
9-
MONGODB_URL= #Mongodb URI to connect to the mongo database server.
10-
MYSQL_HOST= #Mysql host to connect to the mongo database server.
11-
MYSQL_DATABASE= #Mysql database to connect to the mongo database server.
12-
MYSQL_USER= #Mysql username to connect to the mongo database server.
13-
MYSQL_PASSWORD= #Mysql password to connect to the mongo database server.
1+
NODE_ENV=development
2+
PORT=8080
3+
MONGODB_URI=mongodb://127.0.0.1:27017/expressjs_template
4+
MONGODB_DB_NAME=expressjs_template
5+
JWT_SECRET=change-me-change-me-change-me-change
6+
JWT_ACCESS_EXPIRATION_MINUTES=30
7+
JWT_REFRESH_EXPIRATION_DAYS=30
8+
LOG_LEVEL=info
9+
CORS_ORIGIN=http://localhost:3000
10+
SESSION_SECRET=change-me-change-me-change-me-change
11+
SESSION_NAME=sid
12+
SESSION_IDLE_TIMEOUT_MINUTES=30
13+
SESSION_COOKIE_SECURE=false
14+
TRUST_PROXY=false

jest.config.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
module.exports = {
2+
testEnvironment: 'node',
3+
verbose: true,
4+
setupFiles: ['<rootDir>/src/tests/jest.setup.js'],
5+
testMatch: ['**/src/tests/**/*.test.js'],
6+
collectCoverageFrom: ['src/**/*.js', '!src/tests/**'],
7+
};

0 commit comments

Comments
 (0)