also looking at this
Deploy: uniform auth session model (main → production)
#7
282 files
+3028
-64856
| @@ -1,439 +0,0 @@ | ||
| 1 | --- | |
| 2 | title: Middleware | |
| 3 | description: Learn how to create and use middleware in Stacks applications | |
| 4 | --- | |
| 5 | ||
| 6 | ## Middleware Parameters | |
| 7 | ||
| 8 | ### Passing Parameters | |
| 9 | ||
| 10 | Pass parameters to middleware using the colon syntax: | |
| 11 | ||
| 12 | ```typescript | |
| 13 | ||
| 14 | // Throttle: 60 requests per minute | |
| 15 | route.post('/api/data', 'Actions/DataAction') | |
| 16 | .middleware('throttle:60,1') | |
| 17 | ||
| 18 | // Abilities: require 'read' and 'write' abilities | |
| 19 | route.post('/posts', 'Actions/PostStoreAction') | |
| 20 | .middleware('abilities:read,write') | |
| 21 | ||
| 22 | // Environment: only run in production | |
| 23 | route.get('/metrics', 'Actions/MetricsAction') | |
| 24 | .middleware('env:production') | |
| 25 | ||
| 26 | ``` | |
| 27 | ||
| 28 | ### Accessing Parameters in Middleware | |
| 29 | ||
| 30 | ```typescript | |
| 31 | ||
| 32 | // app/Middleware/Abilities.ts | |
| 33 | import type { Request } from '@stacksjs/router' | |
| 34 | import { HttpError } from '@stacksjs/error-handling' | |
| 35 | import { Middleware } from '@stacksjs/router' | |
| 36 | ||
| 37 | export default new Middleware({ | |
| 38 | name: 'abilities', | |
| 39 | priority: 2, | |
| 40 | ||
| 41 | async handle(request: Request) { | |
| 42 | // Parameters are available via _middlewareParams | |
| 43 | const requiredAbilities = (request as any)._middlewareParams?.abilities?.split(',') || [] | |
| 44 | ||
| 45 | if (requiredAbilities.length === 0) { | |
| 46 | return // No abilities required | |
| 47 | } | |
| 48 | ||
| 49 | const token = (request as any)._currentAccessToken | |
| 50 | if (!token) { | |
| 51 | throw new HttpError(401, 'Unauthenticated.') | |
| 52 | } | |
| 53 | ||
| 54 | const tokenAbilities: string[] = token.abilities || [] | |
| 55 | ||
| 56 | // Wildcard grants all permissions | |
| 57 | if (tokenAbilities.includes('_')) { | |
| 58 | return | |
| 59 | } | |
| 60 | ||
| 61 | // Check each required ability | |
| 62 | for (const ability of requiredAbilities) { | |
| 63 | if (!tokenAbilities.includes(ability.trim())) { | |
| 64 | throw new HttpError(403, `Missing required ability: ${ability.trim()}`) | |
| 65 | } | |
| 66 | } | |
| 67 | }, | |
| 68 | }) | |
| 69 | ||
| 70 | ``` | |
| 71 | ||
| 72 | ## Terminable Middleware | |
| 73 | ||
| 74 | Terminable middleware can perform actions after the response has been sent: | |
| 75 | ||
| 76 | ```typescript | |
| 77 | ||
| 78 | // app/Middleware/LogResponse.ts | |
| 79 | import { Middleware } from '@stacksjs/router' | |
| 80 | import { log } from '@stacksjs/logging' | |
| 81 | ||
| 82 | export default new Middleware({ | |
| 83 | name: 'LogResponse', | |
| 84 | priority: 100, // Run late | |
| 85 | ||
| 86 | handle(request) { | |
| 87 | const startTime = Date.now() | |
| 88 | ;(request as any)._startTime = startTime | |
| 89 | }, | |
| 90 | ||
| 91 | // Called after response is sent | |
| 92 | terminate(request, response) { | |
| 93 | const startTime = (request as any)._startTime || Date.now() | |
| 94 | const duration = Date.now() - startTime | |
| 95 | ||
| 96 | log.info(`[${request.method}] ${request.url} - ${response.status} (${duration}ms)`) | |
| 97 | }, | |
| 98 | }) | |
| 99 | ||
| 100 | ``` | |
| 101 | ||
| 102 | ## Built-in Middleware | |
| 103 | ||
| 104 | ### Auth Middleware | |
| 105 | ||
| 106 | Validates bearer tokens and authenticates users: | |
| 107 | ||
| 108 | ```typescript | |
| 109 | ||
| 110 | route.get('/me', 'Actions/AuthUserAction').middleware('auth') | |
| 111 | ||
| 112 | ``` | |
| 113 | ||
| 114 | The auth middleware: | |
| 115 | ||
| 116 | - Extracts the Bearer token from Authorization header | |
| 117 | - Validates the token | |
| 118 | - Attaches the user to `request._authenticatedUser` | |
| 119 | - Attaches the token to `request._currentAccessToken` | |
| 120 | ||
| 121 | ### Abilities Middleware | |
| 122 | ||
| 123 | Checks if the authenticated user's token has required abilities: | |
| 124 | ||
| 125 | ```typescript | |
| 126 | ||
| 127 | // Require 'admin' ability | |
| 128 | route.get('/admin', 'Actions/AdminAction') | |
| 129 | .middleware('auth') | |
| 130 | .middleware('abilities:admin') | |
| 131 | ||
| 132 | // Require multiple abilities | |
| 133 | route.post('/posts', 'Actions/PostAction') | |
| 134 | .middleware('auth') | |
| 135 | .middleware('abilities:posts:create,posts:update') | |
| 136 | ||
| 137 | ``` | |
| 138 | ||
| 139 | ### Throttle Middleware | |
| 140 | ||
| 141 | Rate limits requests: | |
| 142 | ||
| 143 | ```typescript | |
| 144 | ||
| 145 | // 60 requests per minute | |
| 146 | route.post('/api/submit', 'Actions/SubmitAction') | |
| 147 | .middleware('throttle:60,1') | |
| 148 | ||
| 149 | // 10 requests per hour | |
| 150 | route.post('/expensive-operation', 'Actions/ExpensiveAction') | |
| 151 | .middleware('throttle:10,60') | |
| 152 | ||
| 153 | ``` | |
| 154 | ||
| 155 | ### Environment Middleware | |
| 156 | ||
| 157 | Restricts routes to specific environments: | |
| 158 | ||
| 159 | ```typescript | |
| 160 | ||
| 161 | // Only in local environment | |
| 162 | route.get('/debug', 'Actions/DebugAction') | |
| 163 | .middleware('env:local') | |
| 164 | ||
| 165 | // Only in production | |
| 166 | route.get('/metrics', 'Actions/MetricsAction') | |
| 167 | .middleware('env:production') | |
| 168 | ||
| 169 | // Only in development | |
| 170 | route.get('/test', 'Actions/TestAction') | |
| 171 | .middleware('env:development') | |
| 172 | ||
| 173 | ``` | |
| 174 | ||
| 175 | ### Maintenance Middleware | |
| 176 | ||
| 177 | Blocks requests when application is in maintenance mode: | |
| 178 | ||
| 179 | ```typescript | |
| 180 | ||
| 181 | route.group({ middleware: 'maintenance' }, () => { | |
| 182 | // These routes will return 503 during maintenance | |
| 183 | route.get('/api/data', 'Actions/DataAction') | |
| 184 | }) | |
| 185 | ||
| 186 | ``` | |
| 187 | ||
| 188 | ## Middleware Priority | |
| 189 | ||
| 190 | ### Setting Priority | |
| 191 | ||
| 192 | Lower priority numbers run first: | |
| 193 | ||
| 194 | ```typescript | |
| 195 | ||
| 196 | export default new Middleware({ | |
| 197 | name: 'Auth', | |
| 198 | priority: 1, // Runs before priority 2 | |
| 199 | ||
| 200 | handle(request) { | |
| 201 | // Authentication logic | |
| 202 | }, | |
| 203 | }) | |
| 204 | ||
| 205 | export default new Middleware({ | |
| 206 | name: 'Abilities', | |
| 207 | priority: 2, // Runs after priority 1 | |
| 208 | ||
| 209 | handle(request) { | |
| 210 | // Ability checking (needs authenticated user) | |
| 211 | }, | |
| 212 | }) | |
| 213 | ||
| 214 | ``` | |
| 215 | ||
| 216 | ### Execution Order | |
| 217 | ||
| 218 | 1. Global middleware (in order of registration) | |
| 219 | 2. Route group middleware (in order of definition) | |
| 220 | 3. Route-specific middleware (in order of chaining) | |
| 221 | ||
| 222 | ## Creating Custom Middleware | |
| 223 | ||
| 224 | ### Logger Middleware | |
| 225 | ||
| 226 | ```typescript | |
| 227 | ||
| 228 | // app/Middleware/Logger.ts | |
| 229 | import { Middleware } from '@stacksjs/router' | |
| 230 | import { log } from '@stacksjs/logging' | |
| 231 | ||
| 232 | export default new Middleware({ | |
| 233 | name: 'Logger', | |
| 234 | priority: 0, // Run first | |
| 235 | ||
| 236 | handle(request) { | |
| 237 | const timestamp = new Date().toISOString() | |
| 238 | log.info(`[${timestamp}] ${request.method} ${request.url}`) | |
| 239 | }, | |
| 240 | }) | |
| 241 | ||
| 242 | ``` | |
| 243 | ||
| 244 | ### CORS Middleware | |
| 245 | ||
| 246 | ```typescript | |
| 247 | ||
| 248 | // app/Middleware/Cors.ts | |
| 249 | import { Middleware } from '@stacksjs/router' | |
| 250 | ||
| 251 | export default new Middleware({ | |
| 252 | name: 'Cors', | |
| 253 | priority: 0, | |
| 254 | ||
| 255 | handle(request) { | |
| 256 | // CORS is typically handled at the response level | |
| 257 | // This middleware can set up request-level CORS checks | |
| 258 | const origin = request.headers.get('Origin') | |
| 259 | ||
| 260 | if (origin && !isAllowedOrigin(origin)) { | |
| 261 | throw new HttpError(403, 'Origin not allowed') | |
| 262 | } | |
| 263 | }, | |
| 264 | }) | |
| 265 | ||
| 266 | function isAllowedOrigin(origin: string): boolean { | |
| 267 | const allowedOrigins = ['https://example.com', 'https://app.example.com'] | |
| 268 | return allowedOrigins.includes(origin) | |
| 269 | } | |
| 270 | ||
| 271 | ``` | |
| 272 | ||
| 273 | ### Request Sanitization Middleware | |
| 274 | ||
| 275 | ```typescript | |
| 276 | ||
| 277 | // app/Middleware/Sanitize.ts | |
| 278 | import { Middleware } from '@stacksjs/router' | |
| 279 | ||
| 280 | export default new Middleware({ | |
| 281 | name: 'Sanitize', | |
| 282 | priority: 5, | |
| 283 | ||
| 284 | handle(request) { | |
| 285 | // Sanitize all string inputs | |
| 286 | if ((request as any).jsonBody) { | |
| 287 | sanitizeObject((request as any).jsonBody) | |
| 288 | } | |
| 289 | if ((request as any).formBody) { | |
| 290 | sanitizeObject((request as any).formBody) | |
| 291 | } | |
| 292 | }, | |
| 293 | }) | |
| 294 | ||
| 295 | function sanitizeObject(obj: Record<string, any>): void { | |
| 296 | for (const key in obj) { | |
| 297 | if (typeof obj[key] === 'string') { | |
| 298 | obj[key] = obj[key].trim() | |
| 299 | } else if (typeof obj[key] === 'object' && obj[key] !== null) { | |
| 300 | sanitizeObject(obj[key]) | |
| 301 | } | |
| 302 | } | |
| 303 | } | |
| 304 | ||
| 305 | ``` | |
| 306 | ||
| 307 | ## Edge Cases and Gotchas | |
| 308 | ||
| 309 | ### Middleware Order with Groups | |
| 310 | ||
| 311 | When using nested groups, middleware stacks: | |
| 312 | ||
| 313 | ```typescript | |
| 314 | ||
| 315 | route.group({ middleware: 'auth' }, () => { | |
| 316 | // 'auth' middleware applies here | |
| 317 | ||
| 318 | route.group({ middleware: 'logger' }, () => { | |
| 319 | // Both 'auth' AND 'logger' apply here | |
| 320 | route.get('/data', 'Actions/DataAction') | |
| 321 | }) | |
| 322 | }) | |
| 323 | ||
| 324 | ``` | |
| 325 | ||
| 326 | ### Async Middleware Errors | |
| 327 | ||
| 328 | Always throw `HttpError` for proper error responses: | |
| 329 | ||
| 330 | ```typescript | |
| 331 | ||
| 332 | import { HttpError } from '@stacksjs/error-handling' | |
| 333 | ||
| 334 | export default new Middleware({ | |
| 335 | name: 'CustomAuth', | |
| 336 | ||
| 337 | async handle(request) { | |
| 338 | try { | |
| 339 | await validateRequest(request) | |
| 340 | } catch (error) { | |
| 341 | // Throw HttpError for proper status codes | |
| 342 | throw new HttpError(401, 'Authentication failed') | |
| 343 | } | |
| 344 | }, | |
| 345 | }) | |
| 346 | ||
| 347 | ``` | |
| 348 | ||
| 349 | ### Middleware Short-Circuiting | |
| 350 | ||
| 351 | When middleware throws an error, the request chain stops: | |
| 352 | ||
| 353 | ```typescript | |
| 354 | ||
| 355 | export default new Middleware({ | |
| 356 | name: 'BlockedRoute', | |
| 357 | ||
| 358 | handle() { | |
| 359 | // This stops all further processing | |
| 360 | throw new HttpError(403, 'This route is blocked') | |
| 361 | }, | |
| 362 | }) | |
| 363 | ||
| 364 | ``` | |
| 365 | ||
| 366 | ### Accessing Request Data | |
| 367 | ||
| 368 | After body parsing, data is available via: | |
| 369 | ||
| 370 | ```typescript | |
| 371 | ||
| 372 | handle(request) { | |
| 373 | // JSON body | |
| 374 | const jsonData = (request as any).jsonBody | |
| 375 | ||
| 376 | // Form data | |
| 377 | const formData = (request as any).formBody | |
| 378 | ||
| 379 | // Files | |
| 380 | const files = (request as any).files | |
| 381 | ||
| 382 | // Route parameters | |
| 383 | const params = request.params | |
| 384 | ||
| 385 | // Query parameters | |
| 386 | const query = (request as any).query | |
| 387 | } | |
| 388 | ||
| 389 | ``` | |
| 390 | ||
| 391 | ## API Reference | |
| 392 | ||
| 393 | ### Middleware Class | |
| 394 | ||
| 395 | ```typescript | |
| 396 | ||
| 397 | class Middleware { | |
| 398 | constructor(options: { | |
| 399 | name: string | |
| 400 | priority?: number | |
| 401 | handle: (request: Request) => void | Promise<void> | |
| 402 | terminate?: (request: Request, response: Response) => void | Promise<void> | |
| 403 | }) | |
| 404 | } | |
| 405 | ||
| 406 | ``` | |
| 407 | ||
| 408 | ### HttpError Class | |
| 409 | ||
| 410 | ```typescript | |
| 411 | ||
| 412 | class HttpError extends Error { | |
| 413 | constructor(statusCode: number, message: string) | |
| 414 | ||
| 415 | statusCode: number | |
| 416 | message: string | |
| 417 | } | |
| 418 | ||
| 419 | ``` | |
| 420 | ||
| 421 | ### Request Extensions | |
| 422 | ||
| 423 | After middleware processing, the request object includes: | |
| 424 | ||
| 425 | | Property | Type | Description | | |
| 426 | |----------|------|-------------| | |
| 427 | | `_authenticatedUser` | `User` | Authenticated user (after auth middleware) | | |
| 428 | | `_currentAccessToken` | `Token` | Current access token (after auth middleware) | | |
| 429 | | `_middlewareParams` | `Record<string, string>` | Middleware parameters | | |
| 430 | | `jsonBody` | `object` | Parsed JSON body | | |
| 431 | | `formBody` | `object` | Parsed form data | | |
| 432 | | `files` | `Record<string, File>` | Uploaded files | | |
| 433 | ||
| 434 | ## Related Documentation | |
| 435 | ||
| 436 | - [Routing](/basics/routing) - Learn about route definitions | |
| 437 | - [Actions](/basics/actions) - Creating action handlers | |
| 438 | - [Error Handling](/basics/error-handling) - Handling middleware errors | |
| 439 | - [Authentication](/features/authentication) - Authentication system | |