kempo-server 1.2.1 → 1.4.1
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 +209 -4
- package/builtinMiddleware.js +136 -0
- package/defaultConfig.js +36 -0
- package/docs/configuration.html +117 -0
- package/docs/examples.html +199 -0
- package/docs/getting-started.html +70 -0
- package/docs/index.html +51 -330
- package/docs/middleware.html +145 -0
- package/docs/request-response.html +93 -0
- package/docs/routing.html +75 -0
- package/example-middleware.js +23 -0
- package/example.config.json +50 -0
- package/middlewareRunner.js +25 -0
- package/package.json +1 -1
- package/router.js +125 -64
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
<html lang="en" theme="auto">
|
|
2
|
+
<head>
|
|
3
|
+
<meta charset='utf-8'>
|
|
4
|
+
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
|
|
5
|
+
<title>Middleware - Kempo Server</title>
|
|
6
|
+
<meta name='viewport' content='width=device-width, initial-scale=1'>
|
|
7
|
+
<link rel="stylesheet" href="essential.css" />
|
|
8
|
+
</head>
|
|
9
|
+
<body>
|
|
10
|
+
<main>
|
|
11
|
+
<a href="./" class="btn">Home</a>
|
|
12
|
+
<h1>Middleware</h1>
|
|
13
|
+
<p>Kempo Server includes a powerful middleware system that allows you to add functionality like authentication, logging, CORS, compression, and more.</p>
|
|
14
|
+
|
|
15
|
+
<h2>How Middleware Works</h2>
|
|
16
|
+
<p>Middleware functions run before your route handlers and can:</p>
|
|
17
|
+
<ul>
|
|
18
|
+
<li>Modify request and response objects</li>
|
|
19
|
+
<li>Add new properties to requests (authentication, user data, etc.)</li>
|
|
20
|
+
<li>Handle requests entirely (authentication checks, rate limiting)</li>
|
|
21
|
+
<li>Log requests and responses</li>
|
|
22
|
+
<li>Add security headers</li>
|
|
23
|
+
<li>Compress responses</li>
|
|
24
|
+
</ul>
|
|
25
|
+
|
|
26
|
+
<h2>Built-in Middleware</h2>
|
|
27
|
+
<p>Kempo Server includes several built-in middleware options that you can enable and configure:</p>
|
|
28
|
+
|
|
29
|
+
<h3>CORS (Cross-Origin Resource Sharing)</h3>
|
|
30
|
+
<p>Enable Cross-Origin Resource Sharing to allow requests from different domains:</p>
|
|
31
|
+
<pre><code class="hljs json">{<br /> <span class="hljs-attr">"middleware"</span>: {<br /> <span class="hljs-attr">"cors"</span>: {<br /> <span class="hljs-attr">"enabled"</span>: <span class="hljs-literal">true</span>,<br /> <span class="hljs-attr">"origin"</span>: <span class="hljs-string">"*"</span>,<br /> <span class="hljs-attr">"methods"</span>: [<span class="hljs-string">"GET"</span>, <span class="hljs-string">"POST"</span>, <span class="hljs-string">"PUT"</span>, <span class="hljs-string">"DELETE"</span>],<br /> <span class="hljs-attr">"headers"</span>: [<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"Authorization"</span>],<br /> <span class="hljs-attr">"credentials"</span>: <span class="hljs-literal">true</span><br /> }<br /> }<br />}</code></pre>
|
|
32
|
+
|
|
33
|
+
<h4>CORS Configuration Options</h4>
|
|
34
|
+
<ul>
|
|
35
|
+
<li><code>origin</code> - Allowed origins (<code>"*"</code> for all, or specific domains)</li>
|
|
36
|
+
<li><code>methods</code> - Allowed HTTP methods</li>
|
|
37
|
+
<li><code>headers</code> - Allowed request headers</li>
|
|
38
|
+
<li><code>credentials</code> - Allow credentials (cookies, authorization headers)</li>
|
|
39
|
+
<li><code>maxAge</code> - How long browsers can cache preflight responses</li>
|
|
40
|
+
</ul>
|
|
41
|
+
|
|
42
|
+
<h3>Compression</h3>
|
|
43
|
+
<p>Automatically compress responses with gzip to reduce bandwidth:</p>
|
|
44
|
+
<pre><code class="hljs json">{<br /> <span class="hljs-attr">"middleware"</span>: {<br /> <span class="hljs-attr">"compression"</span>: {<br /> <span class="hljs-attr">"enabled"</span>: <span class="hljs-literal">true</span>,<br /> <span class="hljs-attr">"threshold"</span>: <span class="hljs-number">1024</span>,<br /> <span class="hljs-attr">"level"</span>: <span class="hljs-number">6</span><br /> }<br /> }<br />}</code></pre>
|
|
45
|
+
|
|
46
|
+
<h4>Compression Configuration Options</h4>
|
|
47
|
+
<ul>
|
|
48
|
+
<li><code>threshold</code> - Minimum size in bytes before compression is applied</li>
|
|
49
|
+
<li><code>level</code> - Compression level (1-9, where 9 is best compression)</li>
|
|
50
|
+
<li><code>filter</code> - Function to determine which responses to compress</li>
|
|
51
|
+
</ul>
|
|
52
|
+
|
|
53
|
+
<h3>Rate Limiting</h3>
|
|
54
|
+
<p>Limit the number of requests per client to prevent abuse:</p>
|
|
55
|
+
<pre><code class="hljs json">{<br /> <span class="hljs-attr">"middleware"</span>: {<br /> <span class="hljs-attr">"rateLimit"</span>: {<br /> <span class="hljs-attr">"enabled"</span>: <span class="hljs-literal">true</span>,<br /> <span class="hljs-attr">"maxRequests"</span>: <span class="hljs-number">100</span>,<br /> <span class="hljs-attr">"windowMs"</span>: <span class="hljs-number">60000</span>,<br /> <span class="hljs-attr">"message"</span>: <span class="hljs-string">"Too many requests, please try again later."</span><br /> }<br /> }<br />}</code></pre>
|
|
56
|
+
|
|
57
|
+
<h4>Rate Limiting Configuration Options</h4>
|
|
58
|
+
<ul>
|
|
59
|
+
<li><code>maxRequests</code> - Maximum number of requests per window</li>
|
|
60
|
+
<li><code>windowMs</code> - Time window in milliseconds</li>
|
|
61
|
+
<li><code>message</code> - Error message to send when limit is exceeded</li>
|
|
62
|
+
<li><code>statusCode</code> - HTTP status code to return (default: 429)</li>
|
|
63
|
+
</ul>
|
|
64
|
+
|
|
65
|
+
<h3>Security Headers</h3>
|
|
66
|
+
<p>Add security headers to responses to protect against common attacks:</p>
|
|
67
|
+
<pre><code class="hljs json">{<br /> <span class="hljs-attr">"middleware"</span>: {<br /> <span class="hljs-attr">"security"</span>: {<br /> <span class="hljs-attr">"enabled"</span>: <span class="hljs-literal">true</span>,<br /> <span class="hljs-attr">"headers"</span>: {<br /> <span class="hljs-attr">"X-Content-Type-Options"</span>: <span class="hljs-string">"nosniff"</span>,<br /> <span class="hljs-attr">"X-Frame-Options"</span>: <span class="hljs-string">"DENY"</span>,<br /> <span class="hljs-attr">"X-XSS-Protection"</span>: <span class="hljs-string">"1; mode=block"</span>,<br /> <span class="hljs-attr">"Strict-Transport-Security"</span>: <span class="hljs-string">"max-age=31536000; includeSubDomains"</span>,<br /> <span class="hljs-attr">"Referrer-Policy"</span>: <span class="hljs-string">"strict-origin-when-cross-origin"</span><br /> }<br /> }<br /> }<br />}</code></pre>
|
|
68
|
+
|
|
69
|
+
<h4>Common Security Headers</h4>
|
|
70
|
+
<ul>
|
|
71
|
+
<li><code>X-Content-Type-Options</code> - Prevents MIME type sniffing</li>
|
|
72
|
+
<li><code>X-Frame-Options</code> - Prevents clickjacking attacks</li>
|
|
73
|
+
<li><code>X-XSS-Protection</code> - Enables XSS filtering</li>
|
|
74
|
+
<li><code>Strict-Transport-Security</code> - Enforces HTTPS connections</li>
|
|
75
|
+
<li><code>Content-Security-Policy</code> - Controls resource loading</li>
|
|
76
|
+
<li><code>Referrer-Policy</code> - Controls referrer information</li>
|
|
77
|
+
</ul>
|
|
78
|
+
|
|
79
|
+
<h2>Custom Middleware</h2>
|
|
80
|
+
<p>Create your own middleware by writing JavaScript files and referencing them in your config:</p>
|
|
81
|
+
<pre><code class="hljs json">{<br /> <span class="hljs-attr">"middleware"</span>: {<br /> <span class="hljs-attr">"custom"</span>: [<br /> <span class="hljs-string">"./middleware/auth.js"</span>,<br /> <span class="hljs-string">"./middleware/logging.js"</span>,<br /> <span class="hljs-string">"./middleware/analytics.js"</span><br /> ]<br /> }<br />}</code></pre>
|
|
82
|
+
|
|
83
|
+
<h3>Custom Middleware Structure</h3>
|
|
84
|
+
<p>A custom middleware file must export a default function that returns a middleware function:</p>
|
|
85
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// middleware/example.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function">(<span class="hljs-params">config</span>) =></span> {<br /> <span class="hljs-keyword">return</span> <span class="hljs-keyword">async</span> <span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =></span> {<br /> <span class="hljs-comment">// Your middleware logic here</span><br /> <span class="hljs-keyword">await</span> <span class="hljs-title function_">next</span>();<br /> };<br />};</code></pre>
|
|
86
|
+
|
|
87
|
+
<h3>Middleware Function Parameters</h3>
|
|
88
|
+
<ul>
|
|
89
|
+
<li><code>config</code> - Configuration object (can be used for middleware settings)</li>
|
|
90
|
+
<li><code>req</code> - Request object (can be modified)</li>
|
|
91
|
+
<li><code>res</code> - Response object (can be modified)</li>
|
|
92
|
+
<li><code>next</code> - Function to call the next middleware or route handler</li>
|
|
93
|
+
</ul>
|
|
94
|
+
|
|
95
|
+
<h2>Middleware Examples</h2>
|
|
96
|
+
|
|
97
|
+
<h3>Authentication Middleware</h3>
|
|
98
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// middleware/auth.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function">(<span class="hljs-params">config</span>) =></span> {<br /> <span class="hljs-keyword">return</span> <span class="hljs-keyword">async</span> <span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =></span> {<br /> <span class="hljs-keyword">const</span> token = req.<span class="hljs-property">headers</span>.<span class="hljs-property">authorization</span>;<br /> <br /> <span class="hljs-keyword">if</span> (token) {<br /> <span class="hljs-keyword">try</span> {<br /> <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> <span class="hljs-title function_">verifyToken</span>(token.<span class="hljs-title function_">replace</span>(<span class="hljs-string">'Bearer '</span>, <span class="hljs-string">''</span>));<br /> req.<span class="hljs-property">user</span> = user;<br /> req.<span class="hljs-property">permissions</span> = <span class="hljs-keyword">await</span> <span class="hljs-title function_">getUserPermissions</span>(user.<span class="hljs-property">id</span>);<br /> req.<span class="hljs-property">hasPermission</span> = <span class="hljs-function">(<span class="hljs-params">permission</span>) =></span> req.<span class="hljs-property">permissions</span>.<span class="hljs-title function_">includes</span>(permission);<br /> } <span class="hljs-keyword">catch</span> (error) {<br /> <span class="hljs-comment">// Token is invalid, but don't block the request</span><br /> req.<span class="hljs-property">user</span> = <span class="hljs-literal">null</span>;<br /> }<br /> } <span class="hljs-keyword">else</span> {<br /> req.<span class="hljs-property">user</span> = <span class="hljs-literal">null</span>;<br /> }<br /> <br /> <span class="hljs-keyword">await</span> <span class="hljs-title function_">next</span>();<br /> };<br />};<br /><br /><span class="hljs-comment">// Helper functions (you would implement these)</span><br /><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">verifyToken</span>(<span class="hljs-params">token</span>) </span>{<br /> <span class="hljs-comment">// Verify JWT token or session token</span><br /> <span class="hljs-comment">// Return user object if valid, throw error if invalid</span><br />}<br /><br /><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUserPermissions</span>(<span class="hljs-params">userId</span>) </span>{<br /> <span class="hljs-comment">// Fetch user permissions from database</span><br /> <span class="hljs-comment">// Return array of permission strings</span><br />}</code></pre>
|
|
99
|
+
|
|
100
|
+
<h3>Logging Middleware</h3>
|
|
101
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// middleware/logging.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function">(<span class="hljs-params">config</span>) =></span> {<br /> <span class="hljs-keyword">return</span> <span class="hljs-keyword">async</span> <span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =></span> {<br /> <span class="hljs-keyword">const</span> startTime = <span class="hljs-built_in">Date</span>.<span class="hljs-title function_">now</span>();<br /> <span class="hljs-keyword">const</span> { method, path, headers } = req;<br /> <br /> <span class="hljs-comment">// Log request</span><br /> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`[${new Date().toISOString()}] ${method} ${path}`</span>);<br /> <br /> <span class="hljs-comment">// Store original response methods</span><br /> <span class="hljs-keyword">const</span> originalSend = res.<span class="hljs-property">send</span>;<br /> <span class="hljs-keyword">const</span> originalJson = res.<span class="hljs-property">json</span>;<br /> <span class="hljs-keyword">const</span> originalHtml = res.<span class="hljs-property">html</span>;<br /> <br /> <span class="hljs-comment">// Override response methods to log response</span><br /> res.<span class="hljs-property">send</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>) {<br /> <span class="hljs-keyword">const</span> duration = <span class="hljs-built_in">Date</span>.<span class="hljs-title function_">now</span>() - startTime;<br /> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`[${new Date().toISOString()}] ${method} ${path} - ${res.statusCode || 200} - ${duration}ms`</span>);<br /> <span class="hljs-keyword">return</span> <span class="hljs-title function_">originalSend</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, data);<br /> };<br /> <br /> res.<span class="hljs-property">json</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>) {<br /> <span class="hljs-keyword">const</span> duration = <span class="hljs-built_in">Date</span>.<span class="hljs-title function_">now</span>() - startTime;<br /> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`[${new Date().toISOString()}] ${method} ${path} - ${res.statusCode || 200} - ${duration}ms`</span>);<br /> <span class="hljs-keyword">return</span> <span class="hljs-title function_">originalJson</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, data);<br /> };<br /> <br /> <span class="hljs-keyword">await</span> <span class="hljs-title function_">next</span>();<br /> };<br />};</code></pre>
|
|
102
|
+
|
|
103
|
+
<h3>Analytics Middleware</h3>
|
|
104
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// middleware/analytics.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function">(<span class="hljs-params">config</span>) =></span> {<br /> <span class="hljs-keyword">return</span> <span class="hljs-keyword">async</span> <span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =></span> {<br /> <span class="hljs-keyword">const</span> userAgent = req.<span class="hljs-title function_">get</span>(<span class="hljs-string">'user-agent'</span>) || <span class="hljs-string">'Unknown'</span>;<br /> <span class="hljs-keyword">const</span> referer = req.<span class="hljs-title function_">get</span>(<span class="hljs-string">'referer'</span>) || <span class="hljs-string">'Direct'</span>;<br /> <span class="hljs-keyword">const</span> ip = req.<span class="hljs-property">headers</span>[<span class="hljs-string">'x-forwarded-for'</span>] || req.<span class="hljs-property">connection</span>.<span class="hljs-property">remoteAddress</span>;<br /> <br /> <span class="hljs-comment">// Track page view</span><br /> <span class="hljs-keyword">await</span> <span class="hljs-title function_">trackPageView</span>({<br /> <span class="hljs-attr">path</span>: req.<span class="hljs-property">path</span>,<br /> <span class="hljs-attr">method</span>: req.<span class="hljs-property">method</span>,<br /> <span class="hljs-attr">userAgent</span>,<br /> <span class="hljs-attr">referer</span>,<br /> <span class="hljs-attr">ip</span>,<br /> <span class="hljs-attr">timestamp</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>()<br /> });<br /> <br /> <span class="hljs-keyword">await</span> <span class="hljs-title function_">next</span>();<br /> };<br />};<br /><br /><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">trackPageView</span>(<span class="hljs-params">data</span>) </span>{<br /> <span class="hljs-comment">// Send analytics data to your tracking service</span><br /> <span class="hljs-comment">// or save to database</span><br />}</code></pre>
|
|
105
|
+
|
|
106
|
+
<h3>Request Validation Middleware</h3>
|
|
107
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// middleware/validation.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function">(<span class="hljs-params">config</span>) =></span> {<br /> <span class="hljs-keyword">return</span> <span class="hljs-keyword">async</span> <span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =></span> {<br /> <span class="hljs-comment">// Add validation helpers to request object</span><br /> req.<span class="hljs-property">validate</span> = {<br /> <span class="hljs-attr">email</span>: <span class="hljs-function">(<span class="hljs-params">value</span>) =></span> {<br /> <span class="hljs-keyword">const</span> emailRegex = <span class="hljs-regexp">/^[^\s@]+@[^\s@]+\.[^\s@]+$/</span>;<br /> <span class="hljs-keyword">return</span> emailRegex.<span class="hljs-title function_">test</span>(value);<br /> },<br /> <span class="hljs-attr">required</span>: <span class="hljs-function">(<span class="hljs-params">value</span>) =></span> {<br /> <span class="hljs-keyword">return</span> value !== <span class="hljs-literal">undefined</span> && value !== <span class="hljs-literal">null</span> && value !== <span class="hljs-string">''</span>;<br /> },<br /> <span class="hljs-attr">minLength</span>: <span class="hljs-function">(<span class="hljs-params">value, min</span>) =></span> {<br /> <span class="hljs-keyword">return</span> <span class="hljs-keyword">typeof</span> value === <span class="hljs-string">'string'</span> && value.<span class="hljs-property">length</span> >= min;<br /> },<br /> <span class="hljs-attr">maxLength</span>: <span class="hljs-function">(<span class="hljs-params">value, max</span>) =></span> {<br /> <span class="hljs-keyword">return</span> <span class="hljs-keyword">typeof</span> value === <span class="hljs-string">'string'</span> && value.<span class="hljs-property">length</span> <= max;<br /> }<br /> };<br /> <br /> <span class="hljs-keyword">await</span> <span class="hljs-title function_">next</span>();<br /> };<br />};</code></pre>
|
|
108
|
+
|
|
109
|
+
<h2>Using Enhanced Requests in Routes</h2>
|
|
110
|
+
<p>Once middleware has enhanced your request object, you can use the added properties in your route handlers:</p>
|
|
111
|
+
|
|
112
|
+
<h3>Using Authentication Data</h3>
|
|
113
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// api/user/profile/GET.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>) </span>{<br /> <span class="hljs-comment">// Check if user is authenticated (added by auth middleware)</span><br /> <span class="hljs-keyword">if</span> (!req.<span class="hljs-property">user</span>) {<br /> <span class="hljs-keyword">return</span> res.<span class="hljs-title function_">status</span>(<span class="hljs-number">401</span>).<span class="hljs-title function_">json</span>({ <span class="hljs-attr">error</span>: <span class="hljs-string">'Authentication required'</span> });<br /> }<br /> <br /> <span class="hljs-comment">// Check permissions (added by auth middleware)</span><br /> <span class="hljs-keyword">if</span> (!req.<span class="hljs-title function_">hasPermission</span>(<span class="hljs-string">'user:read'</span>)) {<br /> <span class="hljs-keyword">return</span> res.<span class="hljs-title function_">status</span>(<span class="hljs-number">403</span>).<span class="hljs-title function_">json</span>({ <span class="hljs-attr">error</span>: <span class="hljs-string">'Insufficient permissions'</span> });<br /> }<br /> <br /> <span class="hljs-keyword">const</span> profile = <span class="hljs-keyword">await</span> <span class="hljs-title function_">getUserProfile</span>(req.<span class="hljs-property">user</span>.<span class="hljs-property">id</span>);<br /> res.<span class="hljs-title function_">json</span>(profile);<br />}</code></pre>
|
|
114
|
+
|
|
115
|
+
<h3>Using Validation Helpers</h3>
|
|
116
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// api/user/POST.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>) </span>{<br /> <span class="hljs-keyword">const</span> { name, email, password } = <span class="hljs-keyword">await</span> req.<span class="hljs-title function_">json</span>();<br /> <span class="hljs-keyword">const</span> errors = [];<br /> <br /> <span class="hljs-comment">// Use validation helpers added by validation middleware</span><br /> <span class="hljs-keyword">if</span> (!req.<span class="hljs-property">validate</span>.<span class="hljs-title function_">required</span>(name)) {<br /> errors.<span class="hljs-title function_">push</span>(<span class="hljs-string">'Name is required'</span>);<br /> }<br /> <br /> <span class="hljs-keyword">if</span> (!req.<span class="hljs-property">validate</span>.<span class="hljs-title function_">required</span>(email)) {<br /> errors.<span class="hljs-title function_">push</span>(<span class="hljs-string">'Email is required'</span>);<br /> } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (!req.<span class="hljs-property">validate</span>.<span class="hljs-title function_">email</span>(email)) {<br /> errors.<span class="hljs-title function_">push</span>(<span class="hljs-string">'Invalid email format'</span>);<br /> }<br /> <br /> <span class="hljs-keyword">if</span> (!req.<span class="hljs-property">validate</span>.<span class="hljs-title function_">minLength</span>(password, <span class="hljs-number">8</span>)) {<br /> errors.<span class="hljs-title function_">push</span>(<span class="hljs-string">'Password must be at least 8 characters'</span>);<br /> }<br /> <br /> <span class="hljs-keyword">if</span> (errors.<span class="hljs-property">length</span> > <span class="hljs-number">0</span>) {<br /> <span class="hljs-keyword">return</span> res.<span class="hljs-title function_">status</span>(<span class="hljs-number">400</span>).<span class="hljs-title function_">json</span>({ errors });<br /> }<br /> <br /> <span class="hljs-comment">// Create user...</span><br /> <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> <span class="hljs-title function_">createUser</span>({ name, email, password });<br /> res.<span class="hljs-title function_">status</span>(<span class="hljs-number">201</span>).<span class="hljs-title function_">json</span>(user);<br />}</code></pre>
|
|
117
|
+
|
|
118
|
+
<h2>Middleware Best Practices</h2>
|
|
119
|
+
|
|
120
|
+
<h3>Order Matters</h3>
|
|
121
|
+
<p>Middleware runs in the order specified in your configuration. Common ordering:</p>
|
|
122
|
+
<ol>
|
|
123
|
+
<li>Security headers (should run first)</li>
|
|
124
|
+
<li>CORS (before authentication)</li>
|
|
125
|
+
<li>Rate limiting (before heavy processing)</li>
|
|
126
|
+
<li>Authentication (before authorization)</li>
|
|
127
|
+
<li>Logging (can be early or late)</li>
|
|
128
|
+
<li>Compression (should run last)</li>
|
|
129
|
+
</ol>
|
|
130
|
+
|
|
131
|
+
<h3>Error Handling</h3>
|
|
132
|
+
<p>Always handle errors gracefully in custom middleware:</p>
|
|
133
|
+
<pre><code class="hljs javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function">(<span class="hljs-params">config</span>) =></span> {<br /> <span class="hljs-keyword">return</span> <span class="hljs-keyword">async</span> <span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =></span> {<br /> <span class="hljs-keyword">try</span> {<br /> <span class="hljs-comment">// Your middleware logic</span><br /> <span class="hljs-keyword">await</span> <span class="hljs-title function_">next</span>();<br /> } <span class="hljs-keyword">catch</span> (error) {<br /> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Middleware error:'</span>, error);<br /> <span class="hljs-comment">// Don't break the request chain</span><br /> <span class="hljs-keyword">await</span> <span class="hljs-title function_">next</span>();<br /> }<br /> };<br />};</code></pre>
|
|
134
|
+
|
|
135
|
+
<h3>Performance Considerations</h3>
|
|
136
|
+
<ul>
|
|
137
|
+
<li>Keep middleware lightweight - avoid heavy processing</li>
|
|
138
|
+
<li>Use async/await properly to avoid blocking</li>
|
|
139
|
+
<li>Cache expensive operations when possible</li>
|
|
140
|
+
<li>Consider the performance impact of middleware order</li>
|
|
141
|
+
</ul>
|
|
142
|
+
</main>
|
|
143
|
+
<div style="height:25vh"></div>
|
|
144
|
+
</body>
|
|
145
|
+
</html>
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
<html lang="en" theme="auto">
|
|
2
|
+
<head>
|
|
3
|
+
<meta charset='utf-8'>
|
|
4
|
+
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
|
|
5
|
+
<title>Request & Response - Kempo Server</title>
|
|
6
|
+
<meta name='viewport' content='width=device-width, initial-scale=1'>
|
|
7
|
+
<link rel="stylesheet" href="essential.css" />
|
|
8
|
+
</head>
|
|
9
|
+
<body>
|
|
10
|
+
<main>
|
|
11
|
+
<a href="./" class="btn">Home</a>
|
|
12
|
+
<h1>Request & Response Objects</h1>
|
|
13
|
+
<p>Learn how to work with HTTP requests and responses in Kempo Server.</p>
|
|
14
|
+
|
|
15
|
+
<h2>Request Object</h2>
|
|
16
|
+
<p>Kempo Server provides a request object that makes working with HTTP requests easier:</p>
|
|
17
|
+
|
|
18
|
+
<h3>Properties</h3>
|
|
19
|
+
<ul>
|
|
20
|
+
<li><code>request.params</code> - Route parameters from dynamic routes (e.g., <code>{ id: "123", info: "info" }</code>)</li>
|
|
21
|
+
<li><code>request.query</code> - Query string parameters as an object (e.g., <code>{ page: "1", limit: "10" }</code>)</li>
|
|
22
|
+
<li><code>request.path</code> - The pathname of the request URL</li>
|
|
23
|
+
<li><code>request.method</code> - HTTP method (GET, POST, etc.)</li>
|
|
24
|
+
<li><code>request.headers</code> - Request headers object</li>
|
|
25
|
+
<li><code>request.url</code> - Full request URL</li>
|
|
26
|
+
</ul>
|
|
27
|
+
|
|
28
|
+
<h3>Methods</h3>
|
|
29
|
+
<ul>
|
|
30
|
+
<li><code>await request.json()</code> - Parse request body as JSON</li>
|
|
31
|
+
<li><code>await request.text()</code> - Get request body as text</li>
|
|
32
|
+
<li><code>await request.body()</code> - Get raw request body as string</li>
|
|
33
|
+
<li><code>await request.buffer()</code> - Get request body as Buffer</li>
|
|
34
|
+
<li><code>request.get(headerName)</code> - Get specific header value</li>
|
|
35
|
+
<li><code>request.is(type)</code> - Check if content-type contains specified type</li>
|
|
36
|
+
</ul>
|
|
37
|
+
|
|
38
|
+
<h2>Response Object</h2>
|
|
39
|
+
<p>Kempo Server also provides a response object that makes sending responses easier:</p>
|
|
40
|
+
|
|
41
|
+
<h3>Methods</h3>
|
|
42
|
+
<ul>
|
|
43
|
+
<li><code>response.json(object)</code> - Send JSON response with automatic content-type</li>
|
|
44
|
+
<li><code>response.send(data)</code> - Send response (auto-detects content type)</li>
|
|
45
|
+
<li><code>response.html(htmlString)</code> - Send HTML response</li>
|
|
46
|
+
<li><code>response.text(textString)</code> - Send plain text response</li>
|
|
47
|
+
<li><code>response.status(code)</code> - Set status code (chainable)</li>
|
|
48
|
+
<li><code>response.set(field, value)</code> - Set header (chainable)</li>
|
|
49
|
+
<li><code>response.type(contentType)</code> - Set content type (chainable)</li>
|
|
50
|
+
<li><code>response.redirect(url, statusCode)</code> - Redirect to URL</li>
|
|
51
|
+
<li><code>response.cookie(name, value, options)</code> - Set cookie</li>
|
|
52
|
+
<li><code>response.clearCookie(name, options)</code> - Clear cookie</li>
|
|
53
|
+
</ul>
|
|
54
|
+
|
|
55
|
+
<h2>Request Examples</h2>
|
|
56
|
+
|
|
57
|
+
<h3>Accessing Route Parameters</h3>
|
|
58
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// api/user/[id]/GET.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { id } = request.params;<br /> <span class="hljs-keyword">const</span> { includeDetails } = request.query;<br /> <br /> <span class="hljs-comment">// Fetch user data from database</span><br /> <span class="hljs-keyword">const</span> userData = <span class="hljs-keyword">await</span> getUserById(id);<br /> <br /> <span class="hljs-keyword">if</span> (!userData) {<br /> <span class="hljs-keyword">return</span> response.status(<span class="hljs-number">404</span>).json({ error: <span class="hljs-string">'User not found'</span> });<br /> }<br /> <br /> response.json(userData);<br />}</code></pre>
|
|
59
|
+
|
|
60
|
+
<h3>Handling JSON Data</h3>
|
|
61
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// api/user/[id]/POST.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { id } = request.params;<br /> <br /> <span class="hljs-keyword">try</span> {<br /> <span class="hljs-keyword">const</span> updateData = <span class="hljs-keyword">await</span> request.json();<br /> <br /> <span class="hljs-comment">// Update user in database</span><br /> <span class="hljs-keyword">const</span> updatedUser = <span class="hljs-keyword">await</span> updateUser(id, updateData);<br /> <br /> response.json(updatedUser);<br /> } <span class="hljs-keyword">catch</span> (error) {<br /> response.status(<span class="hljs-number">400</span>).json({ error: <span class="hljs-string">'Invalid JSON'</span> });<br /> }<br />}</code></pre>
|
|
62
|
+
|
|
63
|
+
<h3>Working with Form Data</h3>
|
|
64
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// contact/POST.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">try</span> {<br /> <span class="hljs-keyword">const</span> body = <span class="hljs-keyword">await</span> request.text();<br /> <span class="hljs-keyword">const</span> formData = <span class="hljs-keyword">new</span> URLSearchParams(body);<br /> <span class="hljs-keyword">const</span> name = formData.get(<span class="hljs-string">'name'</span>);<br /> <span class="hljs-keyword">const</span> email = formData.get(<span class="hljs-string">'email'</span>);<br /> <span class="hljs-keyword">const</span> message = formData.get(<span class="hljs-string">'message'</span>);<br /> <br /> <span class="hljs-comment">// Process form data...</span><br /> <span class="hljs-keyword">await</span> sendContactEmail({ name, email, message });<br /> <br /> response.html(<span class="hljs-string">'<h1>Thank you for your message!</h1>'</span>);<br /> } <span class="hljs-keyword">catch</span> (error) {<br /> response.status(<span class="hljs-number">400</span>).html(<span class="hljs-string">'<h1>Error processing form</h1>'</span>);<br /> }<br />}</code></pre>
|
|
65
|
+
|
|
66
|
+
<h3>Checking Headers</h3>
|
|
67
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// api/upload/POST.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-comment">// Check if request contains JSON data</span><br /> <span class="hljs-keyword">if</span> (request.is(<span class="hljs-string">'application/json'</span>)) {<br /> <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> request.json();<br /> <span class="hljs-comment">// Handle JSON data</span><br /> }<br /> <br /> <span class="hljs-comment">// Check specific headers</span><br /> <span class="hljs-keyword">const</span> authHeader = request.get(<span class="hljs-string">'authorization'</span>);<br /> <span class="hljs-keyword">const</span> userAgent = request.get(<span class="hljs-string">'user-agent'</span>);<br /> <br /> <span class="hljs-comment">// Check request method</span><br /> <span class="hljs-keyword">if</span> (request.method === <span class="hljs-string">'POST'</span>) {<br /> <span class="hljs-comment">// Handle POST request</span><br /> }<br /> <br /> response.json({ success: <span class="hljs-literal">true</span> });<br />}</code></pre>
|
|
68
|
+
|
|
69
|
+
<h2>Response Examples</h2>
|
|
70
|
+
|
|
71
|
+
<h3>Different Response Types</h3>
|
|
72
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// Different response types</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-comment">// JSON response</span><br /> response.json({ message: <span class="hljs-string">'Hello World'</span> });<br /> <br /> <span class="hljs-comment">// HTML response</span><br /> response.html(<span class="hljs-string">'<h1>Hello World</h1>'</span>);<br /> <br /> <span class="hljs-comment">// Text response</span><br /> response.text(<span class="hljs-string">'Hello World'</span>);<br /> <br /> <span class="hljs-comment">// Status code chaining</span><br /> response.status(<span class="hljs-number">201</span>).json({ created: <span class="hljs-literal">true</span> });<br /> <br /> <span class="hljs-comment">// Custom headers</span><br /> response.set(<span class="hljs-string">'X-Custom-Header'</span>, <span class="hljs-string">'value'</span>).json({ data: <span class="hljs-string">'test'</span> });<br /> <br /> <span class="hljs-comment">// Redirect</span><br /> response.redirect(<span class="hljs-string">'/login'</span>);<br /> <br /> <span class="hljs-comment">// Set cookies</span><br /> response.cookie(<span class="hljs-string">'session'</span>, <span class="hljs-string">'abc123'</span>, { httpOnly: <span class="hljs-literal">true</span> }).json({ success: <span class="hljs-literal">true</span> });<br />}</code></pre>
|
|
73
|
+
|
|
74
|
+
<h3>Error Handling</h3>
|
|
75
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// api/user/[id]/DELETE.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { id } = request.params;<br /> <br /> <span class="hljs-keyword">try</span> {<br /> <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> getUserById(id);<br /> <br /> <span class="hljs-keyword">if</span> (!user) {<br /> <span class="hljs-keyword">return</span> response.status(<span class="hljs-number">404</span>).json({<br /> error: <span class="hljs-string">'User not found'</span>,<br /> code: <span class="hljs-string">'USER_NOT_FOUND'</span><br /> });<br /> }<br /> <br /> <span class="hljs-keyword">await</span> deleteUser(id);<br /> <br /> response.status(<span class="hljs-number">200</span>).json({<br /> message: <span class="hljs-string">'User deleted successfully'</span>,<br /> deletedAt: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().toISOString()<br /> });<br /> } <span class="hljs-keyword">catch</span> (error) {<br /> response.status(<span class="hljs-number">500</span>).json({<br /> error: <span class="hljs-string">'Internal server error'</span>,<br /> code: <span class="hljs-string">'INTERNAL_ERROR'</span><br /> });<br /> }<br />}</code></pre>
|
|
76
|
+
|
|
77
|
+
<h3>Content Negotiation</h3>
|
|
78
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// api/user/[id]/GET.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { id } = request.params;<br /> <span class="hljs-keyword">const</span> userData = <span class="hljs-keyword">await</span> getUserById(id);<br /> <br /> <span class="hljs-comment">// Check Accept header to determine response format</span><br /> <span class="hljs-keyword">const</span> acceptHeader = request.get(<span class="hljs-string">'accept'</span>);<br /> <br /> <span class="hljs-keyword">if</span> (acceptHeader && acceptHeader.includes(<span class="hljs-string">'text/html'</span>)) {<br /> <span class="hljs-comment">// Return HTML representation</span><br /> response.html(<span class="hljs-string">`<br /> <div><br /> <h1>${userData.name}</h1><br /> <p>Email: ${userData.email}</p><br /> </div><br /> `</span>);<br /> } <span class="hljs-keyword">else</span> {<br /> <span class="hljs-comment">// Default to JSON</span><br /> response.json(userData);<br /> }<br />}</code></pre>
|
|
79
|
+
|
|
80
|
+
<h3>Working with Cookies</h3>
|
|
81
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// api/auth/login/POST.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { username, password } = <span class="hljs-keyword">await</span> request.json();<br /> <br /> <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> authenticateUser(username, password);<br /> <br /> <span class="hljs-keyword">if</span> (!user) {<br /> <span class="hljs-keyword">return</span> response.status(<span class="hljs-number">401</span>).json({ error: <span class="hljs-string">'Invalid credentials'</span> });<br /> }<br /> <br /> <span class="hljs-comment">// Set session cookie</span><br /> <span class="hljs-keyword">const</span> sessionToken = <span class="hljs-keyword">await</span> createSessionToken(user.id);<br /> <br /> response<br /> .cookie(<span class="hljs-string">'session'</span>, sessionToken, {<br /> httpOnly: <span class="hljs-literal">true</span>,<br /> secure: <span class="hljs-literal">true</span>,<br /> sameSite: <span class="hljs-string">'strict'</span>,<br /> maxAge: <span class="hljs-number">24</span> * <span class="hljs-number">60</span> * <span class="hljs-number">60</span> * <span class="hljs-number">1000</span> <span class="hljs-comment">// 24 hours</span><br /> })<br /> .json({<br /> message: <span class="hljs-string">'Login successful'</span>,<br /> user: {<br /> id: user.id,<br /> username: user.username,<br /> email: user.email<br /> }<br /> });<br />}</code></pre>
|
|
82
|
+
|
|
83
|
+
<h2>Advanced Request Handling</h2>
|
|
84
|
+
|
|
85
|
+
<h3>File Upload Handling</h3>
|
|
86
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// api/upload/POST.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">try</span> {<br /> <span class="hljs-comment">// Get raw buffer for file upload</span><br /> <span class="hljs-keyword">const</span> buffer = <span class="hljs-keyword">await</span> request.buffer();<br /> <span class="hljs-keyword">const</span> contentType = request.get(<span class="hljs-string">'content-type'</span>);<br /> <br /> <span class="hljs-comment">// Save file to disk</span><br /> <span class="hljs-keyword">const</span> filename = <span class="hljs-string">`upload_${Date.now()}.${getExtensionFromMimeType(contentType)}`</span>;<br /> <span class="hljs-keyword">await</span> fs.writeFile(<span class="hljs-string">`./uploads/${filename}`</span>, buffer);<br /> <br /> response.json({<br /> message: <span class="hljs-string">'File uploaded successfully'</span>,<br /> filename: filename,<br /> size: buffer.length<br /> });<br /> } <span class="hljs-keyword">catch</span> (error) {<br /> response.status(<span class="hljs-number">400</span>).json({ error: <span class="hljs-string">'Upload failed'</span> });<br /> }<br />}</code></pre>
|
|
87
|
+
|
|
88
|
+
<h3>Request Validation</h3>
|
|
89
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// api/user/POST.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">try</span> {<br /> <span class="hljs-keyword">const</span> userData = <span class="hljs-keyword">await</span> request.json();<br /> <br /> <span class="hljs-comment">// Validate required fields</span><br /> <span class="hljs-keyword">const</span> requiredFields = [<span class="hljs-string">'name'</span>, <span class="hljs-string">'email'</span>, <span class="hljs-string">'password'</span>];<br /> <span class="hljs-keyword">const</span> missingFields = requiredFields.filter(<span class="hljs-function"><span class="hljs-params">field</span> =></span> !userData[field]);<br /> <br /> <span class="hljs-keyword">if</span> (missingFields.length > <span class="hljs-number">0</span>) {<br /> <span class="hljs-keyword">return</span> response.status(<span class="hljs-number">400</span>).json({<br /> error: <span class="hljs-string">'Missing required fields'</span>,<br /> missingFields<br /> });<br /> }<br /> <br /> <span class="hljs-comment">// Validate email format</span><br /> <span class="hljs-keyword">const</span> emailRegex = <span class="hljs-regexp">/^[^\s@]+@[^\s@]+\.[^\s@]+$/</span>;<br /> <span class="hljs-keyword">if</span> (!emailRegex.test(userData.email)) {<br /> <span class="hljs-keyword">return</span> response.status(<span class="hljs-number">400</span>).json({<br /> error: <span class="hljs-string">'Invalid email format'</span><br /> });<br /> }<br /> <br /> <span class="hljs-comment">// Create user</span><br /> <span class="hljs-keyword">const</span> newUser = <span class="hljs-keyword">await</span> createUser(userData);<br /> <br /> response.status(<span class="hljs-number">201</span>).json({<br /> message: <span class="hljs-string">'User created successfully'</span>,<br /> user: {<br /> id: newUser.id,<br /> name: newUser.name,<br /> email: newUser.email<br /> }<br /> });<br /> } <span class="hljs-keyword">catch</span> (error) {<br /> response.status(<span class="hljs-number">400</span>).json({ error: <span class="hljs-string">'Invalid request data'</span> });<br /> }<br />}</code></pre>
|
|
90
|
+
</main>
|
|
91
|
+
<div style="height:25vh"></div><div style="height:25vh"></div>
|
|
92
|
+
</body>
|
|
93
|
+
</html>
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
<html lang="en" theme="auto">
|
|
2
|
+
<head>
|
|
3
|
+
<meta charset='utf-8'>
|
|
4
|
+
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
|
|
5
|
+
<title>Routes & Routing - Kempo Server</title>
|
|
6
|
+
<meta name='viewport' content='width=device-width, initial-scale=1'>
|
|
7
|
+
<link rel="stylesheet" href="essential.css" />
|
|
8
|
+
</head>
|
|
9
|
+
<body>
|
|
10
|
+
<main>
|
|
11
|
+
<a href="./" class="btn">Home</a>
|
|
12
|
+
<h1>Routes & Routing</h1>
|
|
13
|
+
<p>Learn how Kempo Server's file-based routing system works.</p>
|
|
14
|
+
|
|
15
|
+
<h2>How Routes Work</h2>
|
|
16
|
+
<p>A route is a request to a directory that will be handled by a file. To define routes, create the directory structure to the route and create a file with the name of the method that this file will handle. For example <code>GET.js</code> will handle the <code>GET</code> requests, <code>POST.js</code> will handle the <code>POST</code> requests and so on. Use <code>index.js</code> to handle all request types.</p>
|
|
17
|
+
|
|
18
|
+
<p>The Javascript file must have a <b>default</b> export that is the function that will handle the request. It will be passed a <code>request</code> object and a <code>response</code> object.</p>
|
|
19
|
+
|
|
20
|
+
<p>For example this directory structure:</p>
|
|
21
|
+
<pre><code class="hljs markdown">my/<br />├─ route/<br />│ ├─ GET.js<br />│ ├─ POST.js<br />├─ other/<br />│ ├─ route/<br />│ │ ├─ GET.js<br /></code></pre>
|
|
22
|
+
<p>Would be used to handle <code>GET my/route/</code>, <code>POST my/route/</code> and <code>GET my/other/route/</code></p>
|
|
23
|
+
|
|
24
|
+
<h2 id="htmlRoutes">HTML Routes</h2>
|
|
25
|
+
<p>Just like JS files, HTML files can be used to define a route. Use <code>GET.html</code>, <code>POST.html</code>, etc... to define files that will be served when that route is requested.</p>
|
|
26
|
+
<pre><code class="hljs markdown">my/<br />├─ route/<br />│ ├─ GET.js<br />│ ├─ POST.js<br />├─ other/<br />│ ├─ route/<br />│ │ ├─ GET.js<br />│ ├─ POST.html<br />│ ├─ GET.html<br /></code></pre>
|
|
27
|
+
|
|
28
|
+
<h3><code>index</code> fallbacks</h3>
|
|
29
|
+
<p><code>index.js</code> or <code>index.html</code> will be used as a fallback for all routes if a <i>method</i> file is not defined. In the above examples we do not have any routes defined for <code>DELETE</code>, <code>PUT</code> <code>PATCH</code>, etc... so lets use an <code>index.js</code> and <code>index.html</code> to be a "catch-all" for all the methods we have not created handlers for.</p>
|
|
30
|
+
<pre><code class="hljs markdown">my/<br />├─ route/<br />│ ├─ GET.js<br />│ ├─ POST.js<br />│ ├─ index.js<br />├─ other/<br />│ ├─ route/<br />│ │ ├─ GET.js<br />│ │ ├─ index.js<br />│ ├─ POST.html<br />│ ├─ GET.html<br />│ ├─ index.html<br />├─ index.html<br /></code></pre>
|
|
31
|
+
|
|
32
|
+
<h2>Dynamic Routes</h2>
|
|
33
|
+
<p>A dynamic route is a route with a "param" in its path. To define the dynamic parts of the route just wrap the directory name in square brackets. For example if you wanted to get a users profile, or perform CRUD operations on a user you might create the following directory structure.</p>
|
|
34
|
+
<pre><code class="hljs markdown">api/<br />├─ user/<br />│ ├─ [id]/<br />│ │ ├─ [info]/<br />│ │ │ ├─ GET.js<br />│ │ │ ├─ DELETE.js<br />│ │ │ ├─ PUT.js<br />│ │ │ ├─ POST.js<br />│ │ ├─ GET.js<br /></code></pre>
|
|
35
|
+
<p>When a request is made to <code>/api/user/123/info</code>, the route file <code>api/user/[id]/[info]/GET.js</code> would be executed and receive a request object with <code>request.params</code> containing <code>{ id: "123", info: "info" }</code>.</p>
|
|
36
|
+
|
|
37
|
+
<h2>Route Examples</h2>
|
|
38
|
+
|
|
39
|
+
<h3>Simple API Route</h3>
|
|
40
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// api/hello/GET.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { name } = request.query;<br /> <span class="hljs-keyword">const</span> message = name ? <span class="hljs-string">`Hello ${name}!`</span> : <span class="hljs-string">'Hello World!'</span>;<br /> <br /> response.json({ message });<br />}</code></pre>
|
|
41
|
+
|
|
42
|
+
<h3>Dynamic User Profile Route</h3>
|
|
43
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// api/users/[id]/GET.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { id } = request.params;<br /> <span class="hljs-keyword">const</span> { includeProfile } = request.query;<br /> <br /> <span class="hljs-comment">// Simulate database lookup</span><br /> <span class="hljs-keyword">const</span> user = {<br /> id: id,<br /> name: <span class="hljs-string">`User ${id}`</span>,<br /> email: <span class="hljs-string">`user${id}@example.com`</span><br /> };<br /> <br /> <span class="hljs-keyword">if</span> (includeProfile === <span class="hljs-string">'true'</span>) {<br /> user.profile = {<br /> bio: <span class="hljs-string">`Bio for user ${id}`</span>,<br /> joinDate: <span class="hljs-string">'2024-01-01'</span><br /> };<br /> }<br /> <br /> response.json(user);<br />}</code></pre>
|
|
44
|
+
|
|
45
|
+
<h3>Nested Dynamic Routes</h3>
|
|
46
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// api/users/[id]/posts/[postId]/GET.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { id, postId } = request.params;<br /> <br /> <span class="hljs-keyword">const</span> post = {<br /> id: postId,<br /> userId: id,<br /> title: <span class="hljs-string">`Post ${postId} by User ${id}`</span>,<br /> content: <span class="hljs-string">'This is the post content...'</span>,<br /> createdAt: <span class="hljs-string">'2024-01-01T00:00:00.000Z'</span><br /> };<br /> <br /> response.json(post);<br />}</code></pre>
|
|
47
|
+
|
|
48
|
+
<h3>HTML Route Example</h3>
|
|
49
|
+
<pre><code class="hljs html"><span class="hljs-comment"><!-- pages/about/GET.html --></span><br /><span class="hljs-meta"><!DOCTYPE html></span><br /><span class="hljs-tag"><<span class="hljs-name">html</span>></span><br /><span class="hljs-tag"><<span class="hljs-name">head</span>></span><br /> <span class="hljs-tag"><<span class="hljs-name">title</span>></span>About Us<span class="hljs-tag"></<span class="hljs-name">title</span>></span><br /><span class="hljs-tag"></<span class="hljs-name">head</span>></span><br /><span class="hljs-tag"><<span class="hljs-name">body</span>></span><br /> <span class="hljs-tag"><<span class="hljs-name">h1</span>></span>About Our Company<span class="hljs-tag"></<span class="hljs-name">h1</span>></span><br /> <span class="hljs-tag"><<span class="hljs-name">p</span>></span>We are a company that does amazing things.<span class="hljs-tag"></<span class="hljs-name">p</span>></span><br /><span class="hljs-tag"></<span class="hljs-name">body</span>></span><br /><span class="hljs-tag"></<span class="hljs-name">html</span>></span></code></pre>
|
|
50
|
+
|
|
51
|
+
<h2>Route File Structure Best Practices</h2>
|
|
52
|
+
|
|
53
|
+
<h3>Organize by Feature</h3>
|
|
54
|
+
<pre><code class="hljs markdown">api/<br />├─ auth/<br />│ ├─ login/<br />│ │ ├─ POST.js<br />│ ├─ logout/<br />│ │ ├─ POST.js<br />│ ├─ register/<br />│ │ ├─ POST.js<br />├─ users/<br />│ ├─ [id]/<br />│ │ ├─ GET.js<br />│ │ ├─ PUT.js<br />│ │ ├─ DELETE.js<br />│ ├─ GET.js<br />│ ├─ POST.js<br />├─ posts/<br />│ ├─ [id]/<br />│ │ ├─ GET.js<br />│ │ ├─ PUT.js<br />│ │ ├─ DELETE.js<br />│ ├─ GET.js<br />│ ├─ POST.js<br /></code></pre>
|
|
55
|
+
|
|
56
|
+
<h3>Use Index Files for Fallbacks</h3>
|
|
57
|
+
<p>Use <code>index.js</code> to handle methods not explicitly defined:</p>
|
|
58
|
+
<pre><code class="hljs javascript"><span class="hljs-comment">// api/users/index.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-comment">// Handle any method not explicitly defined</span><br /> response.status(<span class="hljs-number">405</span>).json({<br /> error: <span class="hljs-string">'Method not allowed'</span>,<br /> allowed: [<span class="hljs-string">'GET'</span>, <span class="hljs-string">'POST'</span>]<br /> });<br />}</code></pre>
|
|
59
|
+
|
|
60
|
+
<h2>Static File Serving</h2>
|
|
61
|
+
<p>Any file that doesn't match a route pattern will be served as a static file. This includes:</p>
|
|
62
|
+
<ul>
|
|
63
|
+
<li>HTML files (except route files)</li>
|
|
64
|
+
<li>CSS files</li>
|
|
65
|
+
<li>JavaScript files (except route files)</li>
|
|
66
|
+
<li>Images</li>
|
|
67
|
+
<li>Any other static assets</li>
|
|
68
|
+
</ul>
|
|
69
|
+
|
|
70
|
+
<p>Example static file structure:</p>
|
|
71
|
+
<pre><code class="hljs markdown">public/<br />├─ index.html # Served at /<br />├─ styles.css # Served at /styles.css<br />├─ script.js # Served at /script.js<br />├─ images/<br />│ ├─ logo.png # Served at /images/logo.png<br />├─ api/ # Routes directory<br />│ ├─ hello/GET.js # Route handler<br /></code></pre>
|
|
72
|
+
</main>
|
|
73
|
+
<div style="height:25vh"></div>
|
|
74
|
+
</body>
|
|
75
|
+
</html>
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Example custom middleware file
|
|
2
|
+
// This would be placed in your project directory and referenced in config
|
|
3
|
+
|
|
4
|
+
export default async function authMiddleware(req, res, next) {
|
|
5
|
+
// Example: Check for API key in headers
|
|
6
|
+
const apiKey = req.headers['x-api-key'];
|
|
7
|
+
|
|
8
|
+
// Skip auth for public routes
|
|
9
|
+
if (req.url.startsWith('/public/')) {
|
|
10
|
+
return await next();
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
if (!apiKey || apiKey !== process.env.API_KEY) {
|
|
14
|
+
res.writeHead(401, { 'Content-Type': 'application/json' });
|
|
15
|
+
res.end(JSON.stringify({ error: 'Unauthorized' }));
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Add user info to request for downstream use
|
|
20
|
+
req.user = { authenticated: true, apiKey };
|
|
21
|
+
|
|
22
|
+
await next();
|
|
23
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"allowedMimes": {
|
|
3
|
+
"html": "text/html",
|
|
4
|
+
"css": "text/css",
|
|
5
|
+
"js": "application/javascript",
|
|
6
|
+
"json": "application/json",
|
|
7
|
+
"png": "image/png",
|
|
8
|
+
"jpg": "image/jpeg"
|
|
9
|
+
},
|
|
10
|
+
"middleware": {
|
|
11
|
+
"cors": {
|
|
12
|
+
"enabled": true,
|
|
13
|
+
"origin": ["http://localhost:3000", "https://mydomain.com"],
|
|
14
|
+
"methods": ["GET", "POST", "PUT", "DELETE"],
|
|
15
|
+
"headers": ["Content-Type", "Authorization", "X-API-Key"]
|
|
16
|
+
},
|
|
17
|
+
"compression": {
|
|
18
|
+
"enabled": true,
|
|
19
|
+
"threshold": 512
|
|
20
|
+
},
|
|
21
|
+
"rateLimit": {
|
|
22
|
+
"enabled": true,
|
|
23
|
+
"maxRequests": 50,
|
|
24
|
+
"windowMs": 60000,
|
|
25
|
+
"message": "Rate limit exceeded. Please try again later."
|
|
26
|
+
},
|
|
27
|
+
"security": {
|
|
28
|
+
"enabled": true,
|
|
29
|
+
"headers": {
|
|
30
|
+
"X-Content-Type-Options": "nosniff",
|
|
31
|
+
"X-Frame-Options": "SAMEORIGIN",
|
|
32
|
+
"X-XSS-Protection": "1; mode=block",
|
|
33
|
+
"Strict-Transport-Security": "max-age=31536000; includeSubDomains"
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"logging": {
|
|
37
|
+
"enabled": true,
|
|
38
|
+
"includeUserAgent": true,
|
|
39
|
+
"includeResponseTime": true
|
|
40
|
+
},
|
|
41
|
+
"custom": [
|
|
42
|
+
"./middleware/auth.js",
|
|
43
|
+
"./middleware/analytics.js"
|
|
44
|
+
]
|
|
45
|
+
},
|
|
46
|
+
"customRoutes": {
|
|
47
|
+
"api/*": "./api-handlers/*",
|
|
48
|
+
"/vendor/bootstrap.css": "./node_modules/bootstrap/dist/css/bootstrap.min.css"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Middleware runner for Kempo Server
|
|
2
|
+
export default class MiddlewareRunner {
|
|
3
|
+
constructor() {
|
|
4
|
+
this.middlewares = [];
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
use(middleware) {
|
|
8
|
+
this.middlewares.push(middleware);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
async run(req, res, finalHandler) {
|
|
12
|
+
let index = 0;
|
|
13
|
+
|
|
14
|
+
const next = async () => {
|
|
15
|
+
if (index >= this.middlewares.length) {
|
|
16
|
+
return await finalHandler();
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const middleware = this.middlewares[index++];
|
|
20
|
+
await middleware(req, res, next);
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
await next();
|
|
24
|
+
}
|
|
25
|
+
}
|