nextrush 1.5.0 โ†’ 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,414 +1,1322 @@
1
- # ๐ŸฆŠ NextRush - Learning Project
2
-
3
1
  <div align="center">
4
2
 
5
- [![Learning Project](https://img.shields.io/badge/Status-Learning%20Project-orange.svg)](https://github.com/0xTanzim/nextRush)
6
- [![NPM Version](https://img.shields.io/npm/v/nextrush.svg)](https://www.npmjs.com/package/nextrush)
7
- [![TypeScript](https://img.shields.io/badge/TypeScript-Learning-blue.svg)](https://www.typescriptlang.org/)
8
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
3
+ # ๐Ÿš€ NextRush v2
9
4
 
10
- **๐ŸŽ“ My first web framework - Built for learning, not production**
5
+ **Modern, Type-Safe Web Framework for Node.js**
11
6
 
12
- </div>
7
+ _Koa-style Context โ€ข Express-inspired API โ€ข Enterprise Features Built-in_
8
+
9
+ [![npm version](https://img.shields.io/npm/v/nextrush?color=brightgreen&style=for-the-badge)](https://www.npmjs.com/package/nextrush)
10
+ [![Node.js](https://img.shields.io/badge/Node.js-20+-339933?style=for-the-badge&logo=node.js&logoColor=white)](https://nodejs.org/)
11
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.8+-3178C6?style=for-the-badge&logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
12
+ [![License](https://img.shields.io/badge/License-MIT-yellow?style=for-the-badge)](LICENSE)
13
+ [![Tests](https://img.shields.io/badge/Tests-1652%20Passing-brightgreen?style=for-the-badge)](https://github.com/0xTanzim/nextrush)
13
14
 
14
15
  ```typescript
15
16
  import { createApp } from 'nextrush';
16
17
 
17
18
  const app = createApp();
18
19
 
19
- app.get('/', (req, res) => {
20
- res.json({ message: 'Hello NextRush!' });
20
+ app.get('/hello', async ctx => {
21
+ ctx.json({ message: 'Welcome to NextRush v2! ๐ŸŽ‰' });
21
22
  });
22
23
 
23
24
  app.listen(3000);
24
- // ๐Ÿš€ Express.js-compatible API with zero dependencies
25
+ // Server running at http://localhost:3000
25
26
  ```
26
27
 
27
- ## โš ๏ธ **Learning Project Notice**
28
+ [**๐Ÿ“– Documentation**](./docs) โ€ข [**๐ŸŽฎ Examples**](./examples) โ€ข [**๐Ÿš€ Quick Start**](#-quick-start) โ€ข [**๐Ÿ’ก Why NextRush?**](#-why-nextrush-v2)
29
+
30
+ </div>
31
+
32
+ ---
33
+
34
+ ## ๐Ÿ’ก Philosophy
35
+
36
+ **NextRush v2 combines the best of three worlds**: Koa's elegant async context pattern, Express's intuitive helper methods, and Fastify's performance optimizationsโ€”all with **enterprise-grade features built directly into the core**.
28
37
 
29
- This is my **first attempt** at building a Node.js web framework. Created for **educational purposes only**.
38
+ Unlike other frameworks that require dozens of plugins for production use, NextRush v2 includes security middleware, validation, templating, WebSocket support, and advanced logging out of the box. Choose your preferred API style: convenience methods, Express-like helpers, or Fastify-style configuration.
30
39
 
31
- **๐Ÿšจ For Production**: Use [Express.js](https://expressjs.com/), [Fastify](https://fastify.dev/), or [Koa](https://koajs.com/) instead.
40
+ **Built for teams that value type safety, developer experience, and production readiness without the plugin fatigue.**
32
41
 
33
- ## ๐Ÿ† **Latest Benchmark Results** _(July 2025)_
42
+ ---
34
43
 
35
- > **Ultimate Fox Test** - Maximum RPS testing with Apache Bench on Intel i5-8300H, 14GB RAM
44
+ ## ๐ŸŽฏ Why NextRush v2?
36
45
 
37
- ### **๐Ÿฅ‡ Overall Performance Rankings:**
46
+ NextRush v2 represents the evolution of Node.js web frameworks, synthesizing proven patterns from Express, Koa, and Fastify into a unified, type-safe framework with enterprise features integrated at the core.
38
47
 
39
- | Rank | Framework | **Peak RPS** | **Best At** | **Avg Latency** |
40
- | ---- | ------------ | ------------ | --------------- | --------------- |
41
- | ๐Ÿฅ‡ | **Fastify** | **9,491** | Low concurrency | **5.3ms** |
42
- | ๐Ÿฅˆ | **Express** | **7,146** | All loads | **14.0ms** |
43
- | ๐Ÿฅ‰ | **NextRush** | **5,784** | Medium loads | **34.6ms** |
48
+ ### ๐Ÿ† Three API Styles, One Framework
44
49
 
45
- ### **๐Ÿ“Š Detailed Performance by Connection Count:**
50
+ | **Convenience API** | **Enhanced API** | **Configuration API** |
51
+ | ------------------- | ---------------- | --------------------- |
52
+ | `ctx.json()` | `ctx.res.json()` | `{ handler, schema }` |
53
+ | Clean & simple | Express-inspired | Fastify-style |
54
+ | **Recommended** | Familiar pattern | Advanced use cases |
46
55
 
47
- #### **50 Connections (Light Load):**
56
+ ### โšก Performance That Scales
48
57
 
49
- | Framework | RPS | Latency | Status |
50
- | ------------ | --------- | ------- | ------------- |
51
- | **Fastify** | **9,491** | 5.3ms | ๐Ÿ† **Winner** |
52
- | **Express** | **6,934** | 7.2ms | ๐Ÿฅˆ Good |
53
- | **NextRush** | **5,612** | 8.9ms | ๐Ÿฅ‰ Decent |
58
+ - **Zero Dependencies** - Pure Node.js core, minimal footprint
59
+ - **13,261 RPS Average** - Competitive with established frameworks
60
+ - **Optimized Router** - O(1) static path lookup, pre-compiled routes
61
+ - **Memory Efficient** - ~60KB baseline overhead
62
+ - **Smart Caching** - Template caching, efficient buffer management
54
63
 
55
- #### **100 Connections (Medium Load):**
64
+ ### ๐Ÿ›ก๏ธ Enterprise Features Built-In
56
65
 
57
- | Framework | RPS | Latency | Status |
58
- | ------------ | --------- | ------- | ------------- |
59
- | **Express** | **7,146** | 14.0ms | ๐Ÿ† **Winner** |
60
- | **Fastify** | **9,154** | 10.9ms | ๐Ÿฅˆ Close |
61
- | **NextRush** | **5,669** | 17.6ms | ๐Ÿฅ‰ Stable |
66
+ Unlike other frameworks requiring extensive plugin ecosystems, NextRush v2 includes production-ready features in the core:
62
67
 
63
- #### **200 Connections (High Load):**
68
+ ```typescript
69
+ const app = createApp();
64
70
 
65
- | Framework | RPS | Latency | Status |
66
- | ------------ | --------- | ------- | ------------- |
67
- | **Fastify** | **9,405** | 21.3ms | ๐Ÿ† **Winner** |
68
- | **Express** | **6,890** | 29.0ms | ๏ฟฝ Good |
69
- | **NextRush** | **5,784** | 34.6ms | ๐Ÿฅ‰ **Peak** |
71
+ // Security middleware (CORS, Helmet, Rate Limiting)
72
+ app.use(app.cors({ origin: ['https://example.com'] }));
73
+ app.use(app.helmet({ xssFilter: true }));
74
+ app.use(app.rateLimiter({ max: 100, windowMs: 15 * 60 * 1000 }));
70
75
 
71
- #### **500+ Connections (Extreme Load):**
76
+ // Smart body parser with auto-detection
77
+ app.use(app.smartBodyParser({ maxSize: 10 * 1024 * 1024 }));
72
78
 
73
- | Framework | RPS | Latency | Performance |
74
- | ------------ | --------- | ------- | ----------- |
75
- | **Fastify** | **8,598** | 58.2ms | Declining |
76
- | **Express** | **7,068** | 70.7ms | Consistent |
77
- | **NextRush** | **5,539** | 90.3ms | Dropping |
79
+ // Advanced validation & sanitization
80
+ const userData = validateRequest(ctx, userSchema);
81
+ const cleanData = sanitizeInput(userData);
78
82
 
79
- ### **๐ŸŽฏ Performance Analysis:**
83
+ // Custom error classes with contextual information
84
+ throw new NotFoundError('User not found', {
85
+ userId: ctx.params.id,
86
+ suggestion: 'Verify the user ID is correct',
87
+ });
80
88
 
81
- #### **๐Ÿš€ Fastify Strengths:**
89
+ // Event-driven architecture (Simple + CQRS patterns)
90
+ await app.events.emit('user.registered', { userId: user.id });
91
+ await app.eventSystem.dispatch({ type: 'CreateUser', data: {...} });
82
92
 
83
- - **Dominates low concurrency** (50-200 connections)
84
- - **Excellent latency** across all loads
85
- - **9.5K RPS peak** - industry-leading performance
93
+ // Template engine with automatic XSS protection
94
+ await ctx.render('profile.html', { user, isAdmin });
86
95
 
87
- #### **๐Ÿ’ช Express Strengths:**
96
+ // WebSocket support with room management
97
+ wsApp.ws('/chat', socket => {
98
+ socket.join('room1');
99
+ socket.onMessage(data => wsApp.wsBroadcast(data, 'room1'));
100
+ });
88
101
 
89
- - **Most consistent** across all connection counts
90
- - **Handles high loads well** (500+ connections)
91
- - **Proven stability** under stress
102
+ // Structured logging with multiple transports
103
+ ctx.logger.info('User action', { userId, action });
92
104
 
93
- #### **๐ŸŽ“ NextRush Analysis:**
105
+ // Dependency injection container
106
+ const service = container.resolve('UserService');
107
+ ```
108
+
109
+ ### ๐Ÿ›ก๏ธ Type Safety First
110
+
111
+ ```typescript
112
+ // Full TypeScript integration with IntelliSense support
113
+ import type { Context, Middleware, RouteHandler } from 'nextrush';
94
114
 
95
- - **Best at 200 connections** (architectural sweet spot)
96
- - **Competitive performance** for a learning project
97
- - **Room for optimization** - performance gap shows learning opportunities
115
+ app.get('/users/:id', async (ctx: Context) => {
116
+ const userId: string = ctx.params.id; // Type-safe route parameters
117
+ const userData: User = ctx.body; // Type-safe request body
118
+ ctx.json({ user: userData }); // Type-safe response
119
+ });
98
120
 
99
- ### **๏ฟฝ Key Performance Insights:**
121
+ // Type-safe middleware composition
122
+ const authMiddleware: Middleware = async (ctx, next) => {
123
+ ctx.state.user = await validateToken(ctx.headers.authorization);
124
+ await next();
125
+ };
126
+ ```
100
127
 
101
- - **NextRush achieves 61% of Fastify's peak performance** - respectable for first framework
102
- - **Zero memory leaks** detected across all test scenarios
103
- - **Performance gap mainly due to** architecture complexity vs. mature optimization
104
- - **Learning-focused development** prioritized features over raw speed
105
- - **Plugin architecture overhead** impacts performance but provides flexibility
128
+ ### ๐ŸŽญ Choose Your API Style
106
129
 
107
- ### **๐Ÿ”ฌ Test Configuration:**
130
+ ```typescript
131
+ // Convenience Methods (Recommended)
132
+ app.get('/users', async ctx => {
133
+ ctx.json(await getUsers()); // Clean and concise
134
+ });
108
135
 
109
- - **Tool**: Apache Bench (ab) for accurate RPS measurement
110
- - **Requests**: 10,000 per test for statistical significance
111
- - **Duration**: 60-second timeout per test
112
- - **Hardware**: Intel i5-8300H, 14GB RAM, Ubuntu 25.04
113
- - **Node.js**: v24.4.1 (latest LTS)
114
- - **Methodology**: Multiple runs, averaged results
136
+ // Enhanced API (Express-inspired helpers)
137
+ app.get('/users', async ctx => {
138
+ ctx.res.json(await getUsers()); // Familiar Express-like methods
139
+ });
115
140
 
116
- ## โœจ **What Makes NextRush Special**
141
+ // Configuration API (Fastify-style)
142
+ app.get('/users', {
143
+ handler: async ctx => ctx.json(await getUsers()),
144
+ schema: { response: { 200: UserSchema } },
145
+ options: { tags: ['users'] },
146
+ });
147
+ ```
117
148
 
118
- ### **๐Ÿ”ฅ Built-in Features Comparison:**
149
+ ### ๐ŸŒŸ Core Features Comparison
150
+
151
+ | Feature | NextRush v2 | Express | Fastify | Koa |
152
+ | ----------------------------- | --------------- | --------------- | --------------- | --------------- |
153
+ | **Security Middleware** | Built-in | Plugin required | Plugin required | Plugin required |
154
+ | **Validation & Sanitization** | Built-in | Plugin required | Built-in | Plugin required |
155
+ | **Template Engine** | Built-in | Plugin required | Plugin required | Plugin required |
156
+ | **WebSocket Support** | Built-in | Plugin required | Plugin required | Plugin required |
157
+ | **Event System (CQRS)** | Dual system | Plugin required | Plugin required | Plugin required |
158
+ | **Advanced Logging** | Plugin included | Plugin required | Plugin required | Plugin required |
159
+ | **Error Classes** | 8 custom types | Basic | Basic | Basic |
160
+ | **Dependency Injection** | Built-in | Plugin required | Plugin required | Plugin required |
161
+ | **Smart Body Parser** | Auto-detection | Plugin required | Built-in | Plugin required |
162
+ | **Static File Serving** | Plugin included | Built-in | Plugin required | Plugin required |
163
+ | **TypeScript Support** | First-class | Community | First-class | Community |
164
+ | **Dependencies** | Zero | Many | Many | Zero |
165
+ | **Performance (RPS)** | ~13,261 | ~11,030 | ~22,717 | ~17,547 |
119
166
 
120
- | Feature | NextRush | Express | Fastify | Dependencies Needed |
121
- | --------------------------- | -------- | ------- | ------- | ---------------------------- |
122
- | **Zero Dependencies** | โœ… | โŒ | โŒ | NextRush: 0, Others: 10+ |
123
- | **Express Compatible** | โœ… | โœ… | โŒ | Drop-in replacement |
124
- | **TypeScript First** | โœ… | โš ๏ธ | โœ… | Built-in vs. @types packages |
125
- | **Built-in Body Parser** | โœ… | โŒ | โœ… | express requires body-parser |
126
- | **Built-in File Uploads** | โœ… | โŒ | โŒ | express requires multer |
127
- | **Built-in WebSocket** | โœ… | โŒ | โŒ | Others require socket.io |
128
- | **Built-in Templates** | โœ… | โŒ | โŒ | Others require view engines |
129
- | **Built-in Security** | โœ… | โŒ | โŒ | Others require helmet + more |
130
- | **Built-in Rate Limiting** | โœ… | โŒ | โŒ | express-rate-limit needed |
131
- | **Built-in Authentication** | โœ… | โŒ | โŒ | passport + sessions needed |
132
- | **API Documentation** | โœ… | โŒ | โŒ | swagger packages needed |
133
- | **Performance Ranking** | 3rd | 2nd | 1st | Speed vs. Features trade-off |
167
+ ---
134
168
 
135
- ### **๐Ÿ”ฅ Core Features:**
169
+ ## โœจ Comprehensive Feature Set
136
170
 
137
- #### **๐Ÿ›ก๏ธ Security & Validation:**
171
+ <table>
172
+ <tr>
173
+ <td width="50%">
138
174
 
139
- - **Input Validation** - Built-in request validation with custom rules
140
- - **XSS Protection** - Automatic cross-site scripting prevention
141
- - **SQL Injection Prevention** - Query sanitization and parameterization
142
- - **CORS Management** - Flexible cross-origin resource sharing
143
- - **Rate Limiting** - Configurable request throttling per IP/user
175
+ ### Modern Development
144
176
 
145
- #### **๐Ÿ“ File Handling:**
177
+ - **TypeScript First** - Full type safety with IntelliSense
178
+ - **Zero Dependencies** - Pure Node.js, minimal footprint
179
+ - **ESM & CJS** - Universal module compatibility
180
+ - **Plugin System** - Extensible architecture
181
+ - **Smart Body Parser** - Auto-detection & zero-copy operations
182
+ - **Template Engine** - Built-in HTML rendering with auto-escaping
146
183
 
147
- - **Static File Serving** - High-performance with compression & caching
148
- - **File Uploads** - Multipart form data with size limits
149
- - **Download Management** - Secure file downloads with access control
150
- - **Image Processing** - Basic resize and format conversion
184
+ </td>
185
+ <td width="50%">
151
186
 
152
- #### **๐ŸŒ Real-time Features:**
187
+ ### Production Ready
153
188
 
154
- - **WebSocket Support** - Built-in WebSocket server with room management
155
- - **Server-Sent Events** - Real-time data streaming to clients
156
- - **Long Polling** - Fallback for real-time communication
189
+ - **Error Handling** - Custom error classes with context
190
+ - **Advanced Logging** - Structured logs with multiple transports
191
+ - **Security** - CORS, Helmet, Rate Limiting included
192
+ - **Validation** - Schema validation & input sanitization
193
+ - **Testing** - Test-friendly design, 1652 passing tests
194
+ - **Static Files** - High-performance file serving
195
+ - **Compression** - Gzip & Brotli support
157
196
 
158
- #### **๐Ÿ“Š Monitoring & Debugging:**
197
+ </td>
198
+ </tr>
199
+ <tr>
200
+ <td width="50%">
159
201
 
160
- - **Request Metrics** - Built-in performance monitoring
161
- - **Health Checks** - Automated endpoint health verification
162
- - **Error Tracking** - Comprehensive error logging and reporting
163
- - **Memory Monitoring** - Real-time memory usage tracking
202
+ ### Real-time & Events
164
203
 
165
- ### **๐Ÿ—๏ธ Architecture Highlights:**
204
+ - **WebSocket Support** - RFC 6455 compliant implementation
205
+ - **Room Management** - Built-in room system for grouping
206
+ - **Broadcasting** - Efficient message delivery patterns
207
+ - **Event System** - Simple events + CQRS/Event Sourcing
208
+ - **Connection Pooling** - Scalable connection management
209
+ - **Heartbeat** - Automatic connection health monitoring
210
+ - **Pub/Sub** - Event-driven architecture support
166
211
 
167
- #### **Plugin System:**
212
+ </td>
213
+ <td width="50%">
168
214
 
169
- ```typescript
170
- // Load only what you need for maximum performance
171
- const app = createApp({
172
- pluginMode: PluginMode.PERFORMANCE, // Only 4 essential plugins
173
- // vs
174
- pluginMode: PluginMode.FULL, // All 15+ plugins loaded
175
- });
176
- ```
215
+ ### Developer Experience
177
216
 
178
- #### **Memory Efficiency:**
217
+ - **Enhanced Errors** - Contextual debugging information
218
+ - **Request/Response Enhancers** - Express-inspired helpers
219
+ - **Path Utilities** - URL & path manipulation tools
220
+ - **Cookie Utilities** - Type-safe cookie management
221
+ - **Dependency Injection** - Built-in DI container
222
+ - **Dev Warnings** - Common mistake detection
223
+ - **Performance Monitoring** - Built-in metrics collection
179
224
 
180
- - **Zero Dependencies** - No bloated node_modules
181
- - **Smart Caching** - Intelligent memory usage with TTL
182
- - **Buffer Pooling** - Optimized memory allocation for high-traffic
183
- - **Garbage Collection** - Minimal GC pressure design
225
+ </td>
226
+ </tr>
227
+ </table>
184
228
 
185
229
  ## ๐Ÿš€ **Quick Start**
186
230
 
187
- ### **Installation**
231
+ ### Prerequisites
232
+
233
+ - **Node.js**: >= 20.0.0
234
+ - **pnpm**: >= 10.0.0 (recommended) or npm/yarn/bun
235
+
236
+ ### Installation
188
237
 
189
238
  ```bash
190
- # NPM (recommended)
239
+ # pnpm (recommended)
240
+ pnpm add nextrush
241
+
242
+ # npm
191
243
  npm install nextrush
192
244
 
193
- # Yarn
245
+ # yarn
194
246
  yarn add nextrush
195
247
 
196
- # PNPM
197
- pnpm add nextrush
248
+ # bun
249
+ bun add nextrush
198
250
  ```
199
251
 
200
- ### **Basic Usage**
252
+ ### Hello World
201
253
 
202
254
  ```typescript
203
- import { createApp, PluginMode } from 'nextrush';
255
+ import { createApp } from 'nextrush';
204
256
 
205
- // Create app with full features (development)
206
257
  const app = createApp();
207
258
 
208
- // Or create app with performance mode (production)
209
- const productionApp = createApp({
210
- pluginMode: PluginMode.PERFORMANCE, // 4 essential plugins only
211
- enableEvents: false,
212
- enableWebSocket: false,
259
+ app.get('/', async ctx => {
260
+ ctx.json({
261
+ message: 'Hello NextRush v2! ๐Ÿš€',
262
+ timestamp: new Date().toISOString(),
263
+ });
213
264
  });
214
265
 
215
- // Express.js-compatible routes work unchanged
216
- app.get('/api/users/:id', (req, res) => {
217
- const { id } = req.params;
218
- const { format } = req.query;
266
+ app.listen(3000, () => {
267
+ console.log('๐Ÿš€ Server running on http://localhost:3000');
268
+ });
269
+ ```
219
270
 
220
- res.json({
221
- id,
222
- name: 'John Doe',
223
- format: format || 'default',
224
- });
271
+ ### 30-Second API
272
+
273
+ ```typescript
274
+ import { createApp } from 'nextrush';
275
+
276
+ const app = createApp({
277
+ cors: true, // Enable CORS
278
+ debug: true, // Development mode
225
279
  });
226
280
 
227
- // POST with automatic body parsing
228
- app.post('/api/users', (req, res) => {
229
- const userData = req.body; // Automatically parsed JSON
230
- res.status(201).json({ created: userData });
281
+ // Middleware
282
+ app.use(async (ctx, next) => {
283
+ console.log(`๐Ÿ“ ${ctx.method} ${ctx.path}`);
284
+ await next();
231
285
  });
232
286
 
233
- app.listen(3000, () => {
234
- console.log('๐Ÿš€ NextRush server running on http://localhost:3000');
287
+ // Routes with three different styles
288
+ app.get('/simple', async ctx => {
289
+ ctx.json({ style: 'convenience' });
235
290
  });
291
+
292
+ app.get('/express', async ctx => {
293
+ ctx.res.json({ style: 'express-like' });
294
+ });
295
+
296
+ app.post('/fastify', {
297
+ handler: async ctx => ctx.json({ style: 'fastify-style' }),
298
+ schema: {
299
+ body: {
300
+ type: 'object',
301
+ properties: { name: { type: 'string' } },
302
+ },
303
+ },
304
+ });
305
+
306
+ app.listen(3000);
236
307
  ```
237
308
 
238
- ### **๐Ÿ”ฅ Advanced Features**
309
+ ---
310
+
311
+ ## ๐ŸŽญ Multiple API Styles
312
+
313
+ NextRush v2 is **Koa-style at its core** with **three distinct API styles**โ€”choose the approach that best fits your team's preferences:
239
314
 
240
- #### **File Uploads (Built-in)**
315
+ ### Convenience Methods _(Recommended)_
241
316
 
242
317
  ```typescript
243
- // No multer needed - built-in file handling
244
- app.post('/upload', (req, res) => {
245
- const file = req.file('document');
246
- const metadata = req.body;
247
-
248
- if (file) {
249
- res.json({
250
- uploaded: file.filename,
251
- size: file.size,
252
- metadata,
253
- });
254
- } else {
255
- res.status(400).json({ error: 'No file uploaded' });
318
+ app.get('/users/:id', async ctx => {
319
+ const user = await findUser(ctx.params.id);
320
+
321
+ if (!user) {
322
+ ctx.json({ error: 'User not found' }, 404);
323
+ return;
324
+ }
325
+
326
+ ctx.json(user); // Clean and concise
327
+ });
328
+
329
+ app.post('/users', async ctx => {
330
+ const user = await createUser(ctx.body);
331
+ ctx.json(user, 201); // Status code as second parameter
332
+ });
333
+ ```
334
+
335
+ ### Enhanced API _(Express-inspired)_
336
+
337
+ ```typescript
338
+ app.get('/users/:id', async ctx => {
339
+ const user = await findUser(ctx.params.id);
340
+
341
+ if (!user) {
342
+ ctx.res.status(404).json({ error: 'User not found' });
343
+ return;
256
344
  }
345
+
346
+ ctx.res.json(user); // Familiar Express-style methods
347
+ });
348
+
349
+ app.post('/users', async ctx => {
350
+ const user = await createUser(ctx.body);
351
+ ctx.res.status(201).json(user); // Chainable method calls
352
+ });
353
+ ```
354
+
355
+ ### Configuration API _(Fastify-style)_
356
+
357
+ ```typescript
358
+ app.get('/users/:id', {
359
+ handler: async ctx => {
360
+ const user = await findUser(ctx.params.id);
361
+ ctx.json(user || { error: 'Not found' }, user ? 200 : 404);
362
+ },
363
+ schema: {
364
+ params: {
365
+ type: 'object',
366
+ properties: { id: { type: 'string', pattern: '^[0-9]+$' } },
367
+ },
368
+ response: {
369
+ 200: { type: 'object', properties: { id: { type: 'string' } } },
370
+ 404: { type: 'object', properties: { error: { type: 'string' } } },
371
+ },
372
+ },
373
+ options: {
374
+ name: 'getUser',
375
+ description: 'Retrieve user by ID',
376
+ tags: ['users'],
377
+ },
257
378
  });
258
379
  ```
259
380
 
260
- #### **WebSocket Support (Built-in)**
381
+ ---
382
+
383
+ ## ๐ŸŒ Real-time WebSocket Support
384
+
385
+ Production-ready WebSocket server with zero dependencies and full TypeScript support:
261
386
 
262
387
  ```typescript
263
- // No socket.io needed - built-in WebSocket
264
- app.ws('/chat', (ws, req) => {
265
- console.log('New WebSocket connection');
388
+ import { createApp, WebSocketPlugin, withWebSocket } from 'nextrush';
389
+ import type { WSConnection } from 'nextrush';
390
+
391
+ const app = createApp();
392
+
393
+ // Install WebSocket plugin
394
+ const wsPlugin = new WebSocketPlugin({
395
+ path: '/ws',
396
+ heartbeatMs: 30000,
397
+ maxConnections: 1000,
398
+ verifyClient: async req => {
399
+ // Optional: Custom authentication
400
+ const token = new URL(req.url || '', 'http://localhost').searchParams.get(
401
+ 'token'
402
+ );
403
+ return !!token;
404
+ },
405
+ });
406
+ wsPlugin.install(app);
407
+
408
+ // โœ… Get typed WebSocket application (Perfect IntelliSense!)
409
+ const wsApp = withWebSocket(app);
410
+
411
+ // Simple echo server with full type safety
412
+ wsApp.ws('/echo', (socket: WSConnection) => {
413
+ socket.send('Welcome!');
414
+
415
+ socket.onMessage((data: string | Buffer) => {
416
+ socket.send(`Echo: ${data}`);
417
+ });
418
+ });
419
+
420
+ // Room-based chat system
421
+ wsApp.ws('/chat', (socket: WSConnection) => {
422
+ const room = 'general';
423
+
424
+ socket.join(room);
425
+ socket.send(`Joined room: ${room}`);
266
426
 
267
- ws.on('message', (data) => {
268
- // Echo message to all connected clients
269
- app.broadcast('chat', `User: ${data}`);
427
+ socket.onMessage((data: string | Buffer) => {
428
+ // Broadcast to all users in room using app-level method
429
+ wsApp.wsBroadcast(data.toString(), room);
270
430
  });
271
431
 
272
- ws.on('close', () => {
273
- console.log('WebSocket connection closed');
432
+ socket.onClose((code, reason) => {
433
+ console.log(`Client disconnected: ${code} - ${reason}`);
274
434
  });
275
435
  });
436
+
437
+ app.listen(3000);
276
438
  ```
277
439
 
278
- #### **Template Rendering (Built-in)**
440
+ **Client Usage:**
441
+
442
+ ```javascript
443
+ // Browser WebSocket client
444
+ const ws = new WebSocket('ws://localhost:3000/chat');
445
+ ws.onopen = () => {
446
+ console.log('Connected!');
447
+ ws.send('Hello everyone!');
448
+ };
449
+ ws.onmessage = event => console.log('Received:', event.data);
450
+ ws.onerror = error => console.error('Error:', error);
451
+ ws.onclose = () => console.log('Disconnected');
452
+
453
+ // With authentication token
454
+ const wsAuth = new WebSocket('ws://localhost:3000/echo?token=your-jwt-token');
455
+ ```
456
+
457
+ ---
458
+
459
+ ## ๐Ÿ›ก๏ธ Built-in Security Middleware
279
460
 
280
461
  ```typescript
281
- // No view engine setup needed
282
- app.get('/profile/:username', (req, res) => {
283
- const data = {
284
- username: req.params.username,
285
- posts: ['Hello World', 'Learning NextRush'],
286
- };
462
+ import { createApp } from 'nextrush';
463
+
464
+ const app = createApp();
465
+
466
+ // CORS - Cross-Origin Resource Sharing
467
+ app.use(
468
+ app.cors({
469
+ origin: ['https://example.com'],
470
+ credentials: true,
471
+ methods: ['GET', 'POST', 'PUT', 'DELETE'],
472
+ })
473
+ );
474
+
475
+ // Helmet - Security headers
476
+ app.use(
477
+ app.helmet({
478
+ contentSecurityPolicy: true,
479
+ xssFilter: true,
480
+ noSniff: true,
481
+ frameguard: { action: 'deny' },
482
+ })
483
+ );
484
+
485
+ // Rate Limiting - DDoS protection
486
+ app.use(
487
+ app.rateLimiter({
488
+ windowMs: 15 * 60 * 1000, // 15 minutes
489
+ max: 100, // 100 requests per window
490
+ message: 'Too many requests',
491
+ })
492
+ );
493
+
494
+ // Request ID - Request tracing
495
+ app.use(app.requestId());
496
+
497
+ // Response Timer - Performance monitoring
498
+ app.use(app.timer());
499
+ ```
500
+
501
+ **Included Security Features:**
502
+
503
+ - **CORS** - Flexible origin control and credential handling
504
+ - **Helmet** - 15+ security headers preconfigured
505
+ - **Rate Limiting** - IP-based request throttling
506
+ - **XSS Protection** - Automatic escaping in template engine
507
+ - **Request Tracing** - Unique identifiers for request tracking
508
+ - **Response Timing** - Performance measurement headers
509
+
510
+ ---
511
+
512
+ ## ๐Ÿ“ **Comprehensive Validation System**
513
+
514
+ ## ๐Ÿ“ Comprehensive Validation System
287
515
 
288
- // Supports Mustache, Handlebars, EJS
289
- res.render('profile.mustache', data);
516
+ ```typescript
517
+ import { validateRequest, sanitizeInput, ValidationError } from 'nextrush';
518
+
519
+ // Define validation schema
520
+ const userSchema = {
521
+ name: {
522
+ required: true,
523
+ type: 'string',
524
+ minLength: 2,
525
+ maxLength: 50,
526
+ },
527
+ email: {
528
+ required: true,
529
+ type: 'email',
530
+ },
531
+ age: {
532
+ type: 'number',
533
+ min: 18,
534
+ max: 120,
535
+ },
536
+ role: {
537
+ enum: ['user', 'admin', 'moderator'],
538
+ },
539
+ };
540
+
541
+ app.post('/users', async ctx => {
542
+ try {
543
+ // Validate request against schema
544
+ const userData = validateRequest(ctx, userSchema);
545
+
546
+ // Sanitize user input
547
+ const cleanData = sanitizeInput(userData);
548
+
549
+ const user = await createUser(cleanData);
550
+ ctx.json({ user }, 201);
551
+ } catch (error) {
552
+ if (error instanceof ValidationError) {
553
+ ctx.json(
554
+ {
555
+ error: 'Validation failed',
556
+ details: error.errors,
557
+ },
558
+ 400
559
+ );
560
+ }
561
+ }
562
+ });
563
+ ```
564
+
565
+ **Validation Capabilities:**
566
+
567
+ - **Type Checking** - string, number, boolean, email, URL, and more
568
+ - **Length Validation** - minLength, maxLength constraints
569
+ - **Range Validation** - min, max for numeric values
570
+ - **Pattern Matching** - Regular expression validation
571
+ - **Enum Validation** - Restricted value sets
572
+ - **Custom Validation** - Extensible validation functions
573
+ - **XSS Prevention** - Automatic input sanitization
574
+
575
+ ๐Ÿ“š **[Complete Validation Guide โ†’](./docs/api/validation-utilities.md)**
576
+
577
+ **Validation Features:**
578
+
579
+ - **Type Checking** - string, number, boolean, email, URL, etc.
580
+ - **Length Validation** - minLength, maxLength
581
+ - **Range Validation** - min, max for numbers
582
+ - **Pattern Matching** - Regex validation
583
+ - **Enum Validation** - Allowed values
584
+ - **Custom Validation** - Your own validation functions
585
+ - **XSS Prevention** - Auto-sanitization
586
+
587
+ ๐Ÿ“š **[Complete Validation Guide โ†’](./docs/api/validation-utilities.md)**
588
+
589
+ ---
590
+
591
+ ## ๐ŸŽจ Template Engine
592
+
593
+ ```typescript
594
+ import { createApp, TemplatePlugin } from 'nextrush';
595
+
596
+ const app = createApp();
597
+
598
+ // Setup template engine
599
+ const templatePlugin = new TemplatePlugin({
600
+ viewsDir: './views',
601
+ cache: true,
602
+ helpers: {
603
+ formatDate: date => new Date(date).toLocaleDateString(),
604
+ currency: value => `$${Number(value).toFixed(2)}`,
605
+ },
606
+ });
607
+
608
+ templatePlugin.install(app);
609
+
610
+ // Use templates
611
+ app.get('/users/:id', async ctx => {
612
+ const user = await getUser(ctx.params.id);
613
+
614
+ await ctx.render('user-profile.html', {
615
+ title: 'User Profile',
616
+ user,
617
+ isAdmin: user.role === 'admin',
618
+ });
290
619
  });
291
620
  ```
292
621
 
293
- #### **Authentication & Security (Built-in)**
622
+ **views/user-profile.html:**
623
+
624
+ ```html
625
+ <!DOCTYPE html>
626
+ <html>
627
+ <head>
628
+ <title>{{title}}</title>
629
+ </head>
630
+ <body>
631
+ <h1>{{user.name}}</h1>
632
+ <p>Email: {{user.email}}</p>
633
+ <p>Joined: {{user.createdAt | formatDate}}</p>
634
+
635
+ {{#if isAdmin}}
636
+ <button>Admin Panel</button>
637
+ {{/if}}
638
+
639
+ <!-- Loop through items -->
640
+ {{#each user.posts}}
641
+ <article>
642
+ <h2>{{this.title}}</h2>
643
+ <p>{{this.excerpt}}</p>
644
+ </article>
645
+ {{/each}}
646
+ </body>
647
+ </html>
648
+ ```
649
+
650
+ **Template Features:**
651
+
652
+ - **Auto-escaping** - XSS protection by default
653
+ - **Control Structures** - if/else, loops, with blocks
654
+ - **Helpers** - Built-in & custom transformation functions
655
+ - **Partials** - Reusable template components
656
+ - **Layouts** - Consistent page structure
657
+ - **Caching** - Fast production performance
658
+
659
+ ๐Ÿ“š **[Template Engine Documentation โ†’](./docs/api/template-plugin.md)**
660
+
661
+ ---
662
+
663
+ ## ๐Ÿšจ Advanced Error Handling
294
664
 
295
665
  ```typescript
296
- // Built-in JWT and session support
297
- app.post('/login', async (req, res) => {
298
- const { username, password } = req.body;
299
-
300
- if (await validateUser(username, password)) {
301
- const token = req.signJWT({ username }, '24h');
302
- res.json({ token, message: 'Login successful' });
303
- } else {
304
- res.status(401).json({ error: 'Invalid credentials' });
666
+ import {
667
+ HttpError,
668
+ BadRequestError,
669
+ UnauthorizedError,
670
+ ForbiddenError,
671
+ NotFoundError,
672
+ ConflictError,
673
+ UnprocessableEntityError,
674
+ TooManyRequestsError,
675
+ InternalServerError,
676
+ } from 'nextrush';
677
+
678
+ // Custom error classes with proper status codes
679
+ app.get('/users/:id', async ctx => {
680
+ const user = await db.user.findById(ctx.params.id);
681
+
682
+ if (!user) {
683
+ throw new NotFoundError('User not found', {
684
+ userId: ctx.params.id,
685
+ suggestion: 'Check the user ID',
686
+ });
305
687
  }
688
+
689
+ if (ctx.state.user.id !== user.id) {
690
+ throw new ForbiddenError("Cannot access other user's data", {
691
+ requestedUserId: ctx.params.id,
692
+ currentUserId: ctx.state.user.id,
693
+ });
694
+ }
695
+
696
+ ctx.json({ user });
306
697
  });
307
698
 
308
- // Protected route with built-in middleware
309
- app.get('/dashboard', req.requireAuth(), (req, res) => {
310
- res.json({
311
- message: `Welcome ${req.user.username}`,
312
- dashboard: 'data',
699
+ // Global error handler
700
+ app.use(async (ctx, next) => {
701
+ try {
702
+ await next();
703
+ } catch (error) {
704
+ if (error instanceof HttpError) {
705
+ ctx.json(
706
+ {
707
+ error: error.message,
708
+ code: error.code,
709
+ details: error.details,
710
+ },
711
+ error.statusCode
712
+ );
713
+ return;
714
+ }
715
+
716
+ // Unexpected errors
717
+ ctx.json({ error: 'Internal server error' }, 500);
718
+ }
719
+ });
720
+ ```
721
+
722
+ **Error Classes:**
723
+
724
+ - **BadRequestError (400)** - Invalid request data
725
+ - **UnauthorizedError (401)** - Authentication required
726
+ - **ForbiddenError (403)** - Insufficient permissions
727
+ - **NotFoundError (404)** - Resource not found
728
+ - **ConflictError (409)** - Resource conflicts
729
+ - **UnprocessableEntityError (422)** - Business rule violations
730
+ - **TooManyRequestsError (429)** - Rate limit exceeded
731
+ - **InternalServerError (500)** - Server errors
732
+
733
+ ๐Ÿ“š **[Complete Error Handling Guide โ†’](./docs/api/errors.md)**
734
+
735
+ ---
736
+
737
+ ## ๐ŸŽช Event-Driven Architecture
738
+
739
+ NextRush v2 includes dual event systems: Simple Events (Express-style) + Advanced Event System (CQRS/Event Sourcing).
740
+
741
+ ### Simple Events API _(Express-style)_
742
+
743
+ ```typescript
744
+ // Emit events
745
+ await app.events.emit('user.registered', {
746
+ userId: user.id,
747
+ email: user.email,
748
+ });
749
+
750
+ // Listen to events
751
+ app.events.on('user.registered', async data => {
752
+ await sendWelcomeEmail(data.email);
753
+ await createDefaultProfile(data.userId);
754
+ await trackAnalytics('User Registered', data);
755
+ });
756
+
757
+ // One-time handlers
758
+ app.events.once('app.ready', async () => {
759
+ await warmupCache();
760
+ await initializeServices();
761
+ });
762
+ ```
763
+
764
+ ### Advanced Event System _(CQRS/Event Sourcing)_
765
+
766
+ ```typescript
767
+ // Define commands
768
+ interface CreateUserCommand {
769
+ type: 'CreateUser';
770
+ data: { name: string; email: string };
771
+ metadata: { id: string; timestamp: Date; correlationId: string };
772
+ }
773
+
774
+ // Register command handlers
775
+ app.eventSystem.registerCommandHandler(
776
+ 'CreateUser',
777
+ async (command: CreateUserCommand) => {
778
+ const user = await db.user.create(command.data);
779
+
780
+ // Emit domain event
781
+ await app.eventSystem.emit({
782
+ type: 'user.created',
783
+ data: { userId: user.id, email: user.email },
784
+ timestamp: new Date(),
785
+ metadata: {
786
+ aggregateId: user.id,
787
+ version: 1,
788
+ },
789
+ });
790
+
791
+ return user;
792
+ }
793
+ );
794
+
795
+ // Subscribe to domain events
796
+ app.eventSystem.subscribe('user.created', async event => {
797
+ await analytics.track('User Created', {
798
+ userId: event.data.userId,
799
+ correlationId: event.metadata.correlationId,
313
800
  });
314
801
  });
802
+
803
+ // Execute commands with CQRS
804
+ app.post('/users', async ctx => {
805
+ const command: CreateUserCommand = {
806
+ type: 'CreateUser',
807
+ data: ctx.body,
808
+ metadata: {
809
+ id: crypto.randomUUID(),
810
+ timestamp: new Date(),
811
+ correlationId: ctx.id,
812
+ },
813
+ };
814
+
815
+ const user = await app.eventSystem.dispatch(command);
816
+ ctx.json({ user }, 201);
817
+ });
315
818
  ```
316
819
 
317
- ### **๐Ÿ”„ Migrating from Express.js**
820
+ **Event System Features:**
318
821
 
319
- Most Express.js code works **unchanged** with NextRush:
822
+ - **Simple Events** - Express-style emit/on/once patterns
823
+ - **CQRS** - Command Query Responsibility Segregation
824
+ - **Event Sourcing** - Domain event tracking and replay
825
+ - **Saga Patterns** - Complex workflow orchestration
826
+ - **Pub/Sub** - Event broadcasting capabilities
827
+ - **Correlation IDs** - Request tracing across services
828
+ - **Event Store** - Event history and replay functionality
320
829
 
321
- ```diff
322
- - const express = require('express');
323
- - const bodyParser = require('body-parser');
324
- - const cors = require('cors');
325
- - const helmet = require('helmet');
326
- - const multer = require('multer');
830
+ ๐Ÿ“š **[Complete Event System Guide โ†’](./docs/api/events.md)**
327
831
 
328
- + import { createApp } from 'nextrush';
832
+ ---
329
833
 
330
- - const app = express();
331
- - app.use(bodyParser.json());
332
- - app.use(cors());
333
- - app.use(helmet());
334
- - const upload = multer({ dest: 'uploads/' });
834
+ ## ๐Ÿ“Š Advanced Logging Plugin
335
835
 
336
- + const app = createApp(); // All middleware built-in!
836
+ ```typescript
837
+ import { LoggerPlugin } from 'nextrush';
838
+
839
+ // Configure advanced logging
840
+ const loggerPlugin = new LoggerPlugin({
841
+ level: 'info',
842
+ format: 'json',
843
+ transports: [
844
+ {
845
+ type: 'console',
846
+ colorize: true,
847
+ },
848
+ {
849
+ type: 'file',
850
+ filename: 'logs/app.log',
851
+ maxSize: 10485760, // 10MB
852
+ maxFiles: 5,
853
+ },
854
+ {
855
+ type: 'file',
856
+ filename: 'logs/errors.log',
857
+ level: 'error',
858
+ maxSize: 10485760,
859
+ },
860
+ ],
861
+ includeTimestamp: true,
862
+ includeMetadata: true,
863
+ });
337
864
 
338
- // All your existing routes work exactly the same
339
- app.get('/api/users', (req, res) => {
340
- res.json({ users: [] });
865
+ loggerPlugin.install(app);
866
+
867
+ // Use in routes
868
+ app.get('/api/data', async ctx => {
869
+ ctx.logger.info('Fetching data', {
870
+ userId: ctx.state.user?.id,
871
+ endpoint: '/api/data',
872
+ });
873
+
874
+ try {
875
+ const data = await fetchData();
876
+ ctx.logger.debug('Data fetched successfully', { count: data.length });
877
+ ctx.json({ data });
878
+ } catch (error) {
879
+ ctx.logger.error('Failed to fetch data', {
880
+ error: error.message,
881
+ stack: error.stack,
882
+ });
883
+ throw error;
884
+ }
341
885
  });
886
+ ```
887
+
888
+ **Logger Features:**
889
+
890
+ - **Multiple Transports** - Console, file, and custom transports
891
+ - **Log Levels** - debug, info, warn, error, fatal
892
+ - **Structured Logging** - JSON format with metadata
893
+ - **File Rotation** - Size-based and time-based rotation
894
+ - **Colorized Output** - Enhanced development experience
895
+ - **Performance Metrics** - Request timing and throughput tracking
896
+ - **Custom Formatters** - Extensible log formatting
897
+
898
+ ๐Ÿ“š **[Logger Plugin Documentation โ†’](./docs/api/logger-plugin.md)**
899
+
900
+ ---
901
+
902
+ ## ๐Ÿ—๏ธ **Advanced Features**
903
+
904
+ ### Modular Router System
905
+
906
+ ```typescript
907
+ import { createApp, createRouter } from 'nextrush';
908
+
909
+ const app = createApp();
910
+
911
+ // Create sub-routers
912
+ const userRouter = createRouter();
913
+ const adminRouter = createRouter();
914
+
915
+ // User routes
916
+ userRouter.get('/profile', async ctx => ctx.json({ user: 'profile' }));
917
+ userRouter.post('/login', async ctx => ctx.json({ message: 'Logged in' }));
918
+
919
+ // Admin routes
920
+ adminRouter.get('/dashboard', async ctx => ctx.json({ admin: 'dashboard' }));
921
+ adminRouter.get('/users', async ctx => ctx.json({ admin: 'users list' }));
922
+
923
+ // Mount routers
924
+ app.use('/users', userRouter);
925
+ app.use('/admin', adminRouter);
926
+ ```
342
927
 
343
- - app.post('/upload', upload.single('file'), (req, res) => {
344
- + app.post('/upload', (req, res) => {
345
- - res.json({ file: req.file });
346
- + res.json({ file: req.file('file') }); // Built-in file handling
928
+ ### Custom Middleware Development
929
+
930
+ ```typescript
931
+ import type { Middleware, Context } from 'nextrush';
932
+
933
+ // Simple middleware
934
+ const logger: Middleware = async (ctx, next) => {
935
+ const start = Date.now();
936
+ console.log(`๐Ÿ”„ ${ctx.method} ${ctx.path}`);
937
+
938
+ await next();
939
+
940
+ const duration = Date.now() - start;
941
+ console.log(`โœ… ${ctx.status} ${duration}ms`);
942
+ };
943
+
944
+ // Authentication middleware with proper error handling
945
+ const requireAuth: Middleware = async (ctx, next) => {
946
+ const token = ctx.headers.authorization?.replace('Bearer ', '');
947
+
948
+ if (!token) {
949
+ throw new UnauthorizedError('Authentication token required', {
950
+ hint: 'Include Authorization: Bearer <token> header',
951
+ });
952
+ }
953
+
954
+ try {
955
+ ctx.state.user = await validateToken(token);
956
+ await next();
957
+ } catch (error) {
958
+ throw new UnauthorizedError('Invalid authentication token', {
959
+ reason: error.message,
960
+ });
961
+ }
962
+ };
963
+
964
+ // Role-based authorization
965
+ const requireRole = (role: string): Middleware => {
966
+ return async (ctx, next) => {
967
+ if (!ctx.state.user) {
968
+ throw new UnauthorizedError('Authentication required');
969
+ }
970
+
971
+ if (!ctx.state.user.roles.includes(role)) {
972
+ throw new ForbiddenError(`${role} role required`, {
973
+ userRoles: ctx.state.user.roles,
974
+ requiredRole: role,
975
+ });
976
+ }
977
+
978
+ await next();
979
+ };
980
+ };
981
+
982
+ // Rate limiting middleware
983
+ const rateLimiter: Middleware = async (ctx, next) => {
984
+ const key = ctx.ip;
985
+ const limit = 100;
986
+ const windowMs = 15 * 60 * 1000;
987
+
988
+ const requests = await getRequestCount(key, windowMs);
989
+
990
+ if (requests >= limit) {
991
+ throw new TooManyRequestsError('Rate limit exceeded', {
992
+ limit,
993
+ retryAfter: Math.ceil(windowMs / 1000),
994
+ });
995
+ }
996
+
997
+ await incrementRequestCount(key, windowMs);
998
+ await next();
999
+ };
1000
+
1001
+ // Use middleware
1002
+ app.use(logger);
1003
+ app.use('/api', requireAuth);
1004
+ app.use('/admin', requireRole('admin'));
1005
+ ```
1006
+
1007
+ ๐Ÿ“š **[Middleware Development Guide โ†’](./docs/guides/middleware-development.md)**
1008
+
1009
+ ### Enhanced Response Methods
1010
+
1011
+ ```typescript
1012
+ // JSON response with status code
1013
+ app.get('/api/users', async ctx => {
1014
+ const users = await getUsers();
1015
+ ctx.json({ users }, 200);
1016
+ });
1017
+
1018
+ // HTML response
1019
+ app.get('/page', async ctx => {
1020
+ ctx.html('<h1>Welcome to NextRush</h1>');
1021
+ });
1022
+
1023
+ // File download with options
1024
+ app.get('/download', async ctx => {
1025
+ ctx.file('./document.pdf', {
1026
+ filename: 'report.pdf',
1027
+ contentType: 'application/pdf',
1028
+ });
1029
+ });
1030
+
1031
+ // Redirect with status code
1032
+ app.get('/old-url', async ctx => {
1033
+ ctx.redirect('/new-url', 301); // Permanent redirect
1034
+ });
1035
+
1036
+ // CSV export
1037
+ app.get('/export/users', async ctx => {
1038
+ const users = await getUsers();
1039
+ const csv = users.map(u => `${u.name},${u.email}`).join('\n');
1040
+ ctx.csv(`name,email\n${csv}`, 'users.csv');
1041
+ });
1042
+
1043
+ // Stream response
1044
+ app.get('/stream', async ctx => {
1045
+ const stream = fs.createReadStream('./large-file.txt');
1046
+ ctx.stream(stream, 'text/plain');
347
1047
  });
1048
+
1049
+ // Set custom headers
1050
+ app.get('/api/data', async ctx => {
1051
+ ctx.set('X-Custom-Header', 'value');
1052
+ ctx.set('Cache-Control', 'max-age=3600');
1053
+ ctx.json({ data: [] });
1054
+ });
1055
+
1056
+ // Cookie management
1057
+ app.get('/set-cookie', async ctx => {
1058
+ ctx.setCookie('session', 'abc123', {
1059
+ httpOnly: true,
1060
+ secure: true,
1061
+ maxAge: 3600000,
1062
+ sameSite: 'strict',
1063
+ });
1064
+ ctx.json({ message: 'Cookie set' });
1065
+ });
1066
+
1067
+ app.get('/get-cookie', async ctx => {
1068
+ const session = ctx.getCookie('session');
1069
+ ctx.json({ session });
1070
+ });
1071
+ ```
1072
+
1073
+ ๐Ÿ“š **[Enhanced Request/Response API โ†’](./docs/api/enhancers.md)**
1074
+
1075
+ ## ๐Ÿ“– Complete API Reference
1076
+
1077
+ ### Context Object
1078
+
1079
+ ```typescript
1080
+ // ===================== Request Properties =====================
1081
+ ctx.req // Native HTTP request object
1082
+ ctx.res // Enhanced response object
1083
+ ctx.body // Parsed request body (JSON, form, etc.)
1084
+ ctx.method // HTTP method (GET, POST, PUT, DELETE, etc.)
1085
+ ctx.path // Request path (/users/123)
1086
+ ctx.url // Full request URL
1087
+ ctx.query // Query parameters (?page=1 โ†’ { page: '1' })
1088
+ ctx.headers // Request headers (lowercase keys)
1089
+ ctx.params // Route parameters (/users/:id โ†’ { id: '123' })
1090
+ ctx.cookies // Parsed cookies
1091
+ ctx.ip // Client IP address
1092
+ ctx.secure // Is HTTPS?
1093
+ ctx.protocol // Request protocol (http/https)
1094
+ ctx.hostname // Request hostname
1095
+ ctx.origin // Request origin (protocol + host)
1096
+ ctx.state // Custom request-scoped state
1097
+
1098
+ // ===================== Response Methods =====================
1099
+ // Convenience API (Recommended)
1100
+ ctx.json(data, status?) // Send JSON response
1101
+ ctx.html(html, status?) // Send HTML response
1102
+ ctx.text(text, status?) // Send plain text
1103
+ ctx.csv(data, filename?) // Send CSV file
1104
+ ctx.file(path, options?) // Send file download
1105
+ ctx.stream(stream, contentType?) // Send stream response
1106
+ ctx.redirect(url, status?) // Redirect to URL
1107
+
1108
+ // Express-like API (Enhanced)
1109
+ ctx.res.json(data, status?) // Send JSON
1110
+ ctx.res.status(code) // Set status code (chainable)
1111
+ ctx.res.send(data) // Auto-detect content type
1112
+ ctx.res.sendFile(path) // Send file
1113
+ ctx.res.render(template, data) // Render template
1114
+
1115
+ // ===================== Header & Cookie Methods =====================
1116
+ ctx.get(headerName) // Get request header
1117
+ ctx.set(headerName, value) // Set response header
1118
+ ctx.setCookie(name, value, opts) // Set cookie
1119
+ ctx.getCookie(name) // Get cookie value
1120
+ ctx.clearCookie(name) // Delete cookie
1121
+
1122
+ // ===================== Utility Properties =====================
1123
+ ctx.id // Unique request ID
1124
+ ctx.logger // Request-scoped logger
1125
+ ctx.services // DI container services
1126
+ ctx.app // Application instance
348
1127
  ```
349
1128
 
350
- ### **โšก Performance Optimization**
1129
+ ### Application Methods
351
1130
 
352
1131
  ```typescript
353
- // For maximum performance (production)
354
- const app = createApp({
355
- pluginMode: PluginMode.PERFORMANCE,
356
- enableEvents: false,
357
- enableWebSocket: false,
358
- enableMetrics: false,
359
- maxRequestSize: 1024 * 1024, // 1MB limit
360
- timeout: 30000, // 30 second timeout
1132
+ // ===================== HTTP Methods =====================
1133
+ app.get(path, ...handlers) // GET route
1134
+ app.post(path, ...handlers) // POST route
1135
+ app.put(path, ...handlers) // PUT route
1136
+ app.delete(path, ...handlers) // DELETE route
1137
+ app.patch(path, ...handlers) // PATCH route
1138
+ app.head(path, ...handlers) // HEAD route
1139
+ app.options(path, ...handlers) // OPTIONS route
1140
+ app.all(path, ...handlers) // All HTTP methods
1141
+
1142
+ // ===================== Middleware =====================
1143
+ app.use(...middleware) // Global middleware
1144
+ app.use(path, ...middleware) // Path-specific middleware
1145
+
1146
+ // ===================== Built-in Middleware =====================
1147
+ app.cors(options) // CORS middleware
1148
+ app.helmet(options) // Security headers
1149
+ app.rateLimiter(options) // Rate limiting
1150
+ app.compression(options) // Gzip/Brotli compression
1151
+ app.requestId(options) // Request ID tracking
1152
+ app.timer() // Response time header
1153
+ app.smartBodyParser(options) // Auto body parsing
1154
+
1155
+ // ===================== Event System =====================
1156
+ app.events.emit(event, data) // Emit simple event
1157
+ app.events.on(event, handler) // Listen to event
1158
+ app.events.once(event, handler) // One-time listener
1159
+ app.events.off(event, handler?) // Remove listener
1160
+
1161
+ app.eventSystem.dispatch(op) // CQRS dispatch
1162
+ app.eventSystem.executeCommand(c) // Execute command
1163
+ app.eventSystem.executeQuery(q) // Execute query
1164
+ app.eventSystem.subscribe(e, h) // Subscribe to domain event
1165
+
1166
+ // ===================== Server Control =====================
1167
+ app.listen(port, callback?) // Start HTTP server
1168
+ app.close(callback?) // Stop server gracefully
1169
+ ```
1170
+
1171
+ ### Router Methods
1172
+
1173
+ ```typescript
1174
+ // Create router
1175
+ const router = createRouter('/prefix');
1176
+
1177
+ // HTTP methods
1178
+ router.get(path, handler);
1179
+ router.post(path, handler);
1180
+ router.put(path, handler);
1181
+ router.delete(path, handler);
1182
+ router.patch(path, handler);
1183
+
1184
+ // Middleware
1185
+ router.use(middleware);
1186
+
1187
+ // Mount router
1188
+ app.use('/api', router);
1189
+ ```
1190
+
1191
+ ---
1192
+
1193
+ ## ๐Ÿงช Testing
1194
+
1195
+ ```typescript
1196
+ import { createApp } from 'nextrush';
1197
+
1198
+ describe('NextRush Application', () => {
1199
+ it('should handle GET requests', async () => {
1200
+ const app = createApp();
1201
+
1202
+ app.get('/test', async ctx => {
1203
+ ctx.json({ message: 'OK' });
1204
+ });
1205
+
1206
+ // Your test implementation
1207
+ });
361
1208
  });
1209
+ ```
1210
+
1211
+ ---
362
1212
 
363
- // Results in ~20% better performance
364
- // NextRush: 5,784 RPS โ†’ ~7,000 RPS (estimated)
1213
+ ## ๐Ÿ”ฅ Enhanced Body Parser
1214
+
1215
+ Enterprise-grade body parsing with zero-copy operations:
1216
+
1217
+ ```typescript
1218
+ // Auto-parsing (recommended)
1219
+ app.use(app.smartBodyParser());
1220
+
1221
+ // Advanced configuration
1222
+ app.use(
1223
+ app.smartBodyParser({
1224
+ maxSize: 10 * 1024 * 1024, // 10MB
1225
+ enableStreaming: true,
1226
+ autoDetectContentType: true,
1227
+ enableMetrics: true,
1228
+ })
1229
+ );
1230
+
1231
+ // Supports JSON, form-data, text, multipart
1232
+ app.post('/api/data', ctx => {
1233
+ const data = ctx.body; // Already parsed!
1234
+ ctx.json({ received: data });
1235
+ });
365
1236
  ```
366
1237
 
367
- ## ๐Ÿ“š **Learning Documentation**
1238
+ **Features:** Zero-copy buffers โ€ข Auto-detection โ€ข Streaming โ€ข Memory-pooled โ€ข Cross-platform
1239
+
1240
+ ๐Ÿ“š **[Full Documentation โ†’](./docs/api/built-in-middleware.md)**
1241
+
1242
+ ## ๐Ÿ“š Documentation
1243
+
1244
+ Comprehensive guides, API references, and architecture deep-dives:
1245
+
1246
+ ### Getting Started
1247
+
1248
+ - **[Getting Started Guide](./docs/guides/getting-started.md)** - Your first NextRush v2 app in 5 minutes
1249
+ - **[Migration from Express](./docs/guides/migration-guide.md)** - Migrate from Express.js
1250
+ - **[Migration from Fastify](./docs/guides/migration-guide.md)** - Migrate from Fastify
368
1251
 
369
- - **[๐Ÿ“– Lessons Learned](./LESSONS-LEARNED.md)** - My complete learning journey
370
- - **[๐Ÿ“‹ Project Status](./PROJECT-STATUS.md)** - Final achievements and metrics
371
- - **[๐Ÿšช Exit Plan](./EXIT-PLAN.md)** - How to properly conclude a learning project
372
- - **[๐Ÿ“Š Benchmarks](./professional-benchmarks/)** - Complete performance testing suite
1252
+ ### Essential Guides
373
1253
 
374
- ## ๐ŸŽ“ **Educational Value**
1254
+ - **[Routing Guide](./docs/api/routing.md)** - All three routing styles explained (Convenience, Enhanced, Fastify-style)
1255
+ - **[Middleware Development](./docs/guides/middleware-development.md)** - Create custom middleware
1256
+ - **[Plugin Development](./docs/guides/plugin-development.md)** - Build powerful plugins
1257
+ - **[Error Handling Guide](./docs/guides/error-handling.md)** - Robust error management patterns
1258
+ - **[Testing Guide](./docs/guides/testing-guide.md)** - Unit, integration, and E2E testing
1259
+ - **[Production Deployment](./docs/guides/production-deployment.md)** - Deploy to production
375
1260
 
376
- ### **What I Learned:**
1261
+ ### Core API Reference
377
1262
 
378
- - Framework architecture and design patterns
379
- - Plugin systems and extensible architectures
380
- - TypeScript advanced patterns and techniques
381
- - Performance testing and optimization
382
- - NPM package development and publishing
1263
+ - **[Application API](./docs/api/application.md)** - Core application methods and lifecycle
1264
+ - **[Context API](./docs/api/context.md)** - Request/response context (Koa-style)
1265
+ - **[Routing API](./docs/api/routing.md)** - Router and route handlers
1266
+ - **[Middleware API](./docs/api/middleware.md)** - Middleware system and patterns
1267
+ - **[Built-in Middleware](./docs/api/built-in-middleware.md)** - CORS, Helmet, Rate Limiting, Body Parser
1268
+ - **[Events API](./docs/api/events.md)** - Simple Events + Advanced Event System (CQRS)
1269
+ - **[Enhanced Request/Response](./docs/api/enhancers.md)** - Express-like helper methods
383
1270
 
384
- ### **Key Insights:**
1271
+ ### Advanced Features
385
1272
 
386
- - **Architecture planning** is more important than coding speed
387
- - **Simple solutions** often outperform complex optimizations
388
- - **Plugin systems** must be designed from day 1
389
- - **Testing** should come before features, not after
1273
+ - **[Error Handling API](./docs/api/errors.md)** - Custom error classes and error middleware
1274
+ - **[Validation Utilities](./docs/api/validation-utilities.md)** - Schema validation and data sanitization
1275
+ - **[Configuration & Validation](./docs/api/configuration.md)** - Application configuration
1276
+ - **[Path Utilities](./docs/api/path-utilities.md)** - URL and path manipulation helpers
1277
+ - **[Developer Experience](./docs/api/developer-experience.md)** - Enhanced error messages and debugging
390
1278
 
391
- ## ๐Ÿš€ **Next Steps**
1279
+ ### Plugin APIs
392
1280
 
393
- This project achieved its educational goals. The knowledge gained will be applied to **NextRush v2.0** - a complete rewrite with:
1281
+ - **[Logger Plugin](./docs/api/logger-plugin.md)** - Advanced structured logging with transports
1282
+ - **[WebSocket Plugin](./docs/api/websocket-plugin.md)** - Real-time WebSocket communication
1283
+ - **[Static Files Plugin](./docs/api/static-files-plugin.md)** - High-performance static file serving
1284
+ - **[Template Plugin](./docs/api/template-plugin.md)** - HTML template rendering engine
394
1285
 
395
- - โœ… Architecture-first approach
396
- - โœ… Test-driven development
397
- - โœ… Incremental feature addition
398
- - โœ… Performance optimization from day 1
1286
+ ### Architecture Deep-Dives
399
1287
 
400
- ## ๐Ÿ“„ **License**
1288
+ - **[Plugin System](./docs/architecture/plugin-system.md)** - Plugin architecture and lifecycle
1289
+ - **[Dependency Injection](./docs/architecture/dependency-injection.md)** - DI container and service resolution
1290
+ - **[Orchestration System](./docs/architecture/orchestration-system.md)** - Application orchestration patterns
1291
+ - **[Optimized Router](./docs/architecture/optimized-router-deep-dive.md)** - Router internals and performance
401
1292
 
402
- MIT License - see [LICENSE](./LICENSE) file for details.
1293
+ ### Performance & Benchmarks
1294
+
1295
+ - **Benchmarks** - Performance comparisons with Express, Koa, and Fastify
1296
+ - **Performance Guide** - Optimization techniques and best practices
1297
+ - **Memory Management** - Efficient memory usage patterns
1298
+
1299
+ ## ๐Ÿค Contributing
1300
+
1301
+ Contributions are welcome! Please see our [Contributing Guide](CONTRIBUTING.md) for details on how to get started.
1302
+
1303
+ ## ๐Ÿ“„ License
1304
+
1305
+ This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
1306
+
1307
+ ## ๐Ÿ™ Acknowledgments
1308
+
1309
+ - **Express.js** - Intuitive API design patterns
1310
+ - **Koa** - Powerful async middleware architecture
1311
+ - **Fastify** - Object-based route configuration approach
1312
+ - **TypeScript** - Type safety and enhanced developer experience
403
1313
 
404
1314
  ---
405
1315
 
406
1316
  <div align="center">
407
1317
 
408
- **๐ŸŽ“ Successfully completed learning project!**
409
-
410
- _Built with โค๏ธ for education and shared for learning_
1318
+ **Built with precision by [Tanzim Hossain](https://github.com/0xTanzim)**
411
1319
 
412
- [โญ Star on GitHub](https://github.com/0xTanzim/nextRush) โ€ข [๐Ÿ“– Learn More](./LESSONS-LEARNED.md) โ€ข [๐Ÿš€ NextRush v2.0 Coming Soon]
1320
+ [Report Bug](https://github.com/0xTanzim/nextrush/issues) โ€ข [Request Feature](https://github.com/0xTanzim/nextrush/issues) โ€ข [Discussions](https://github.com/0xTanzim/nextrush/discussions)
413
1321
 
414
1322
  </div>