|
1 | | -# Express.js Template Repository |
| 1 | +# Express Enterprise Starter |
2 | 2 |
|
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. |
4 | 4 |
|
5 | | -## Features |
| 5 | +## ✨ Highlights |
6 | 6 |
|
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. |
13 | 16 |
|
14 | | -## Installation |
| 17 | +## 🗂️ Project Structure |
15 | 18 |
|
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 | +``` |
20 | 39 |
|
21 | | -## Usage |
| 40 | +## 🚀 Getting Started |
22 | 41 |
|
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`. |
27 | 56 |
|
28 | | -## Contributors |
| 57 | +## 🔧 Environment Variables |
29 | 58 |
|
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` | |
31 | 75 |
|
32 | | -## License |
| 76 | +## 📚 Available Scripts |
33 | 77 |
|
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. |
0 commit comments