### Complete CORS Configuration Example Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/cors.md A full example demonstrating how to configure CORS with multiple origins, methods, headers, credentials, and max age, integrated into an Itty Router setup. ```typescript import { AutoRouter, cors, withContent, json } from 'itty-router' const { preflight, corsify } = cors({ origin: ['https://example.com', 'https://app.example.com'], allowMethods: ['GET', 'POST', 'PUT', 'DELETE'], allowHeaders: ['Content-Type', 'Authorization'], exposeHeaders: ['X-Total-Count', 'X-RateLimit-Remaining'], credentials: true, maxAge: 86400 // 24 hours }) const router = AutoRouter({ base: '/api', before: [preflight, withContent], finally: [corsify, json] }) router .get('/users', () => [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]) .post('/users', ({ content }) => { return { id: 3, ...content } }) .delete('/users/:id', ({ id }) => { return { deleted: id } }) export default router ``` -------------------------------- ### Basic AutoRouter Setup and Routes Source: https://github.com/kwhitley/itty-router/blob/v5.x/README.md Demonstrates initializing AutoRouter and defining GET routes for string, JSON, and Promise responses. Exports the router for use. ```javascript import { AutoRouter } from 'itty-router' // ~1kB const router = AutoRouter() router .get('/hello/:name', ({ name }) => `Hello, ${name}!`) .get('/json', () => [1,2,3]) .get('/promises', () => Promise.resolve('foo')) export default { ...router } // strips the proxy // that's it ^-^ ``` -------------------------------- ### Usage Example Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/routers.md A comprehensive example demonstrating how to initialize and use the Router with various configurations and route definitions. ```APIDOC ## Usage Example ```typescript import { Router } from 'itty-router' import { json, error, withParams } from 'itty-router' const router = Router({ base: '/api', before: [withParams], catch: error, finally: [json] }) router .get('/users/:id', ({ params }) => ({ user: params.id })) .post('/users', ({ content }) => ({ created: true })) .all('*', () => error(404)) export default { fetch: router.fetch.bind(router) } ``` ``` -------------------------------- ### Auto Router Setup Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/quick-start.md Recommended for beginners, this setup includes a 'batteries-included' configuration with sensible defaults for routing. ```typescript import { AutoRouter } from 'itty-router' const router = AutoRouter() router .get('/hello/:name', ({ name }) => ({ message: `Hello, ${name}!` })) .get('/json', () => [1, 2, 3]) .get('/promises', () => Promise.resolve('foo')) export default router ``` -------------------------------- ### Bun Environment Setup Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/quick-start.md Configure Itty-Router to work within a Bun environment. This example shows how to export a fetch handler for Bun. ```typescript import { AutoRouter } from 'itty-router' const router = AutoRouter() router.get('/hello/:name', ({ name }) => ({ message: `Hello, ${name}!` })) export default { fetch: router.fetch.bind(router), port: 3000 } ``` -------------------------------- ### Complete CORS Example Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/cors.md A comprehensive example demonstrating the integration of `preflight` and `corsify` with `itty-router` for full CORS support. ```APIDOC ## Complete Example ```typescript import { AutoRouter, cors, withContent, json } from 'itty-router' const { preflight, corsify } = cors({ origin: ['https://example.com', 'https://app.example.com'], allowMethods: ['GET', 'POST', 'PUT', 'DELETE'], allowHeaders: ['Content-Type', 'Authorization'], exposeHeaders: ['X-Total-Count', 'X-RateLimit-Remaining'], credentials: true, maxAge: 86400 // 24 hours }) const router = AutoRouter({ base: '/api', before: [preflight, withContent], finally: [corsify, json] }) router .get('/users', () => [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]) .post('/users', ({ content }) => { return { id: 3, ...content } }) .delete('/users/:id', ({ id }) => { return { deleted: id } }) export default router ``` ``` -------------------------------- ### Production Itty-Router Configuration Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/configuration.md A complete example of a production-ready Itty-Router setup, including CORS, middleware, and error handling. ```typescript import { AutoRouter, error, json, cors, withContent, withCookies } from 'itty-router' const { preflight, corsify } = cors({ origin: process.env.ALLOWED_ORIGINS?.split(',') || '*', credentials: true }) const router = AutoRouter({ base: '/api/v1', format: json, before: [ preflight, withContent, withCookies, requestIdMiddleware, rateLimitMiddleware ], catch: (err, request) => { // Log to monitoring service monitoring.captureException(err) // Return safe error response return error(err.status || 500, { error: 'Internal Server Error', requestId: request.id }) }, finally: [ corsify, addSecurityHeaders, addPerformanceMetrics, responseLogger ] }) // Routes... router .get('/health', () => ({ status: 'healthy' })) .get('/users/:id', getUser) .post('/users', createUser) export default router ``` -------------------------------- ### Middleware Composition Example Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/middleware.md Illustrates how to chain multiple middleware functions in the `before` and `finally` arrays for sequential execution. ```APIDOC ## Middleware Composition ```typescript const router = Router({ before: [ withParams, withContent, withCookies, authMiddleware, customLogic ], finally: [ responseLogger, corsHandler, json ] }) ``` ``` -------------------------------- ### Usage Example with Custom Middleware Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/middleware.md Demonstrates how to define and use custom authentication and logging middleware within the itty-router configuration. ```APIDOC ## Usage Example ```typescript import { Router, withParams, json } from 'itty-router' // Custom auth middleware const withAuth = (request) => { const token = request.headers.get('Authorization')?.split(' ')[1] if (!token || !validateToken(token)) { return new Response('Unauthorized', { status: 401 }) } request.user = decodeToken(token) } // Custom logger middleware const withLogging = (response, request) => { console.log(`${request.method} ${request.url} -> ${response.status}`) return response } const router = Router({ before: [withParams, withAuth], finally: [json, withLogging] }) router.get('/secure', ({ user }) => ({ message: `Hello, ${user.name}` })) ``` ``` -------------------------------- ### Simple API Server with AutoRouter Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/INDEX.md A basic example of an API server using `AutoRouter`. Routes are defined using chained HTTP method helpers like `get`, `post`, and `delete`. ```typescript import { AutoRouter } from 'itty-router' const router = AutoRouter() router .get('/users/:id', ({ id }) => ({ user: { id } })) .post('/users', ({ content }) => ({ created: true, user: content })) .delete('/users/:id', ({ id }) => ({ deleted: id })) export default router ``` -------------------------------- ### Router Usage Example Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/routers.md Demonstrates how to configure and use the Router with options like base path, middleware, and error handling. Exports a fetch handler for use in Cloudflare Workers. ```typescript import { Router } from 'itty-router' import { json, error, withParams } from 'itty-router' const router = Router({ base: '/api', before: [withParams], catch: error, finally: [json] }) router .get('/users/:id', ({ params }) => ({ user: params.id })) .post('/users', ({ content }) => ({ created: true })) .all('*', () => error(404)) export default { fetch: router.fetch.bind(router) } ``` -------------------------------- ### Middleware Composition Example Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/middleware.md Chain multiple middleware functions in the 'before' and 'finally' arrays of the Router configuration to control execution order. ```typescript const router = Router({ before: [ withParams, withContent, withCookies, authMiddleware, customLogic ], finally: [ responseLogger, corsHandler, json ] }) ``` -------------------------------- ### HasContent Usage Example Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/types.md Demonstrates using HasContent with the Router and the withContent middleware. This example defines a CreateUserRequest type and accesses its content property. ```typescript import { HasContent, Router, withContent } from 'itty-router' type CreateUserRequest = HasContent<{ name: string email: string }> const router = Router({ before: [withContent] }) router.post('/users', (request: CreateUserRequest) => { const { name, email } = request.content return { created: true, user: { name, email } } }) ``` -------------------------------- ### IRequest Usage Example Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/types.md Demonstrates how to use the IRequest type with the Router. This example shows accessing route, params, and query properties within a handler. ```typescript import { IRequest, Router } from 'itty-router' const router = Router() router.get('/users/:id', (request: IRequest) => { return { route: request.route, id: request.params.id, page: request.query.page } }) ``` -------------------------------- ### 401 Unauthorized Response Example Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/error-handling.md Shows how to throw a `StatusError` with a 401 code when authentication credentials are missing. The response indicates the requirement for authorization. ```javascript router.get('/admin', ({ headers }) => { if (!headers.get('Authorization')) { throw new StatusError(401, 'Missing credentials') } return { message: 'Admin data' } }) ``` -------------------------------- ### Testing CORS Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/cors.md Provides a command-line example for testing CORS configuration. ```APIDOC ## Testing CORS Check if CORS is properly configured: ```bash ``` -------------------------------- ### Usage Example with Custom Middleware Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/middleware.md Integrate custom authentication and logging middleware into an Itty Router by defining them and passing them to the router's configuration. ```typescript import { Router, withParams, json } from 'itty-router' // Custom auth middleware const withAuth = (request) => { const token = request.headers.get('Authorization')?.split(' ')[1] if (!token || !validateToken(token)) { return new Response('Unauthorized', { status: 401 }) } request.user = decodeToken(token) } // Custom logger middleware const withLogging = (response, request) => { console.log(`${request.method} ${request.url} -> ${response.status}`) return response } const router = Router({ before: [withParams, withAuth], finally: [json, withLogging] }) router.get('/secure', ({ user }) => ({ message: `Hello, ${user.name}` })) ``` -------------------------------- ### 404 Not Found Response Example Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/error-handling.md Illustrates how to throw a `StatusError` with a 404 code when a requested resource is not found. The response will contain a default 'Not Found' message. ```javascript router.get('/users/:id', ({ id }) => { const user = findUser(id) if (!user) throw new StatusError(404) return user }) ``` -------------------------------- ### Unit Testing Itty-Router Routes with Bun Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/quick-start.md Write unit tests for your Itty-Router routes using Bun's testing utilities. This example demonstrates testing a GET request. ```typescript import { Router } from 'itty-router' import { expect, test } from 'bun:test' const router = Router() router.get('/users/:id', ({ id }) => ({ id })) test('GET /users/123', async () => { const response = await router.fetch( new Request('https://example.com/users/123') ) const body = await response.json() expect(response.status).toBe(200) expect(body.id).toBe('123') }) ``` -------------------------------- ### RequestHandler Usage Examples Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/types.md Shows two examples of defining RequestHandler functions: one with the default IRequest type and another with additional custom arguments. ```typescript import { RequestHandler, IRequest } from 'itty-router' const handler: RequestHandler = (request) => { return { message: 'Hello' } } const handlerWithArgs: RequestHandler = ( request, customArg ) => { return customArg.process(request) } ``` -------------------------------- ### Simple CORS Setup with AutoRouter Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/quick-start.md Configure basic CORS headers for all routes using `AutoRouter` and the `cors` utility. `preflight` middleware handles OPTIONS requests, and `corsify` adds headers to responses. ```typescript import { AutoRouter, cors } from 'itty-router' const { preflight, corsify } = cors({ origin: '*', allowMethods: ['GET', 'POST'] }) const router = AutoRouter({ before: [preflight], finally: [corsify] }) ``` -------------------------------- ### Create AutoRouter Instance Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/INDEX.md Instantiate the AutoRouter, a batteries-included version of the router. It comes with pre-configured features and is suitable for quick setup. ```typescript import { AutoRouter } from 'itty-router' const router = AutoRouter() ``` -------------------------------- ### Browser Behavior: Simple Requests Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/cors.md Explains how browsers handle simple requests (GET, HEAD, POST with simple headers) which do not require a preflight OPTIONS request. ```APIDOC ## Browser Behavior **Simple Requests (No Preflight):** GET, HEAD, POST with simple headers (Content-Type only): - Sent directly to server - Browser checks response CORS headers - If not allowed, blocks response from JavaScript ``` -------------------------------- ### Cloudflare Workers Basic Route Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/quick-start.md Set up a basic GET route for Cloudflare Workers. Ensure 'itty-router' is installed. ```typescript import { AutoRouter } from 'itty-router' const router = AutoRouter() router.get('/hello/:name', ({ name }) => { return { message: `Hello, ${name}!` } }) export default router ``` -------------------------------- ### Registering HTTP Method Handlers Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/quick-start.md Demonstrates how to register handlers for different HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS) on specific routes. ```typescript router.get('/data', () => []) router.post('/data', () => ({ created: true })) router.put('/data/:id', () => ({ updated: true })) router.patch('/data/:id', () => ({ patched: true })) router.delete('/data/:id', () => ({ deleted: true })) router.head('/data', () => new Response(null, { status: 200 })) router.options('/data', () => new Response(null, { status: 204 })) ``` -------------------------------- ### ResponseHandler Usage Examples Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/types.md Provides examples of ResponseHandler functions for logging and transforming responses. The logger logs request details and the transformer modifies response headers. ```typescript import { ResponseHandler, IRequest } from 'itty-router' const logger: ResponseHandler = (response, request) => { console.log(`${request.method} ${request.url} -> ${response.status}`) return response } const transformer: ResponseHandler = (response) => { response.headers.set('X-Custom', 'value') return response } ``` -------------------------------- ### Full Router with Error Handling Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/quick-start.md This setup provides more control over the request/response lifecycle, including error handling and middleware. ```typescript import { Router, error, json, withParams } from 'itty-router' const router = Router({ before: [withParams], catch: error, finally: [json] }) router.get('/users/:id', ({ id }) => ({ user: { id } })) export default router ``` -------------------------------- ### Hook Execution Order Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/middleware.md Visualizes the order in which different middleware hooks and route handlers are executed within a full router setup. ```APIDOC ## Hook Execution Order When using a full Router with all hooks: 1. **before middleware** — Runs first (can return to skip route matching) 2. **Route matching** — URL pattern matched against registered routes 3. **Route handlers** — Matched route handlers execute in order 4. **catch** — If error thrown, error handler executes 5. **finally middleware** — Runs after route handling or error handling 6. **Response returned** — Final response sent to caller ``` Request ↓ [before] → (early return? → Response) ↓ [match routes] → (no match? → continues to finally) ↓ [route handlers] → (has response? → to finally) ↓ [error?] → (yes? → catch handler → to finally) ↓ [finally] → (transform response) ↓ Response ``` ``` -------------------------------- ### JavaScript Fetch with Credentials Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/cors.md Example of making a JavaScript `fetch` request that includes credentials, such as cookies. The server must explicitly allow credentials via CORS. ```javascript // JavaScript fetch with credentials fetch(url, { credentials: 'include' // Send cookies }) ``` -------------------------------- ### Integrating Error Handling in Itty-Router Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/error-handling.md Shows a complete example of setting up an Itty-Router with a `catch` handler that uses the `error()` function. It includes route definitions that throw `StatusError` for different scenarios like user not found or forbidden access, and a POST route that directly throws an error using `error()`. ```typescript import { Router, error, withParams } from 'itty-router' const router = Router({ before: [withParams], catch: error }) router.get('/users/:id', ({ id }) => { const user = findUser(parseInt(id)) if (!user) { throw new StatusError(404, { error: 'User not found' }) } if (!hasAccess(user)) { throw new StatusError(403, 'Forbidden') } return user }) router.post('/data', () => { throw error(422, { error: 'Unprocessable Entity', field: 'name', reason: 'Name must be at least 3 characters' }) }) ``` -------------------------------- ### Access Route Parameters via request.params Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/middleware.md This example demonstrates accessing route parameters directly from the `request.params` object, which is populated by the `withParams` middleware. This is a straightforward method for retrieving parameter values. ```typescript // Via request.params router.get('/users/:id', (request) => ({ id: request.params.id })) ``` -------------------------------- ### 400 Bad Request with Details Response Example Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/error-handling.md Demonstrates throwing a `StatusError` with a 400 code and a detailed error object when input validation fails. This provides specific feedback on the required field and the reason for failure. ```javascript router.post('/users', ({ content }) => { if (!content.email) { throw new StatusError(400, { error: 'Bad Request', field: 'email', message: 'Email is required' }) } return createUser(content) }) ``` -------------------------------- ### Basic IttyRouter Usage Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/routers.md Instantiate IttyRouter and define a GET route with a named parameter. This is suitable for simple use cases requiring minimal overhead. ```typescript import { IttyRouter } from 'itty-router' const router = IttyRouter() router.get('/:name', ({ params }) => `Hello, ${params.name}!`) export default router ``` -------------------------------- ### ErrorHandler Usage Example Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/types.md Demonstrates an ErrorHandler function that customizes responses based on the error status. It returns specific messages for 404 and other server errors. ```typescript import { ErrorHandler, StatusError, IRequest } from 'itty-router' const handleError: ErrorHandler = (err, request) => { if (err.status === 404) { return { status: 404, message: 'Not Found' } } return { status: 500, message: 'Server Error' } } ``` -------------------------------- ### Basic AutoRouter Usage with Custom Formatter Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/routers.md Instantiate AutoRouter with a custom response formatter and define GET and POST routes. AutoRouter includes features like automatic parameter extraction and JSON error handling. ```typescript import { AutoRouter, error } from 'itty-router' const router = AutoRouter({ format: (body) => new Response(JSON.stringify(body)) }) router .get('/hello/:name', ({ params }) => ({ message: `Hello, ${params.name}!` })) .post('/data', async ({ content }) => ({ saved: content })) export default { fetch: router.fetch.bind(router) } ``` -------------------------------- ### Customizing AutoRouter Defaults Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/routers.md Configure AutoRouter with custom options for response formatting, error handling, and middleware. This example demonstrates using plain text for responses and a custom 404 handler. ```typescript import { AutoRouter, text, error, withContent } from 'itty-router' const router = AutoRouter({ format: text, // Use plain text instead of JSON missing: () => error(410, 'Gone'), // Custom 404 handler before: [withContent], // Add content parsing }) ``` -------------------------------- ### HTTP Method Handlers Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/routers.md The Router instance provides methods to register handlers for various HTTP methods, including GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, and a catch-all 'all' method. ```APIDOC ## HTTP Method Handlers ### router.get(path, ...handlers) #### Description Register GET route handler(s). #### Example ```typescript router.get('/users/:id', (request) => ({ id: request.params.id })) ``` ### router.post(path, ...handlers) #### Description Register POST route handler(s). #### Example ```typescript router.post('/users', (request) => ({ created: true })) ``` ### router.put(path, ...handlers) #### Description Register PUT route handler(s). #### Example ```typescript router.put('/users/:id', (request) => ({ updated: true })) ``` ### router.patch(path, ...handlers) #### Description Register PATCH route handler(s). #### Example ```typescript router.patch('/users/:id', (request) => ({ patched: true })) ``` ### router.delete(path, ...handlers) #### Description Register DELETE route handler(s). #### Example ```typescript router.delete('/users/:id', (request) => ({ deleted: true })) ``` ### router.head(path, ...handlers) #### Description Register HEAD route handler(s). #### Example ```typescript router.head('/users/:id', (request) => new Response(null, { status: 200 })) ``` ### router.options(path, ...handlers) #### Description Register OPTIONS route handler(s). #### Example ```typescript router.options('/users', (request) => new Response(null, { status: 200 })) ``` ### router.all(path, ...handlers) #### Description Register handler for all HTTP methods. #### Example ```typescript router.all('*', (request) => ({ message: 'catch-all' })) ``` ``` -------------------------------- ### Register HTTP Routes Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/INDEX.md Register routes for various HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS) and path patterns. Supports route parameters like ':param' and wildcard paths like '/*'. ```typescript router.get('/path/:param', handler) router.post('/path', handler) router.put('/path/:id', handler) router.patch('/path/:id', handler) router.delete('/path/:id', handler) router.head('/path', handler) router.options('/path', handler) router.all('/path/*', handler) ``` -------------------------------- ### Implementing Catch-All Routes Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/quick-start.md Shows how to use a catch-all route (e.g., `all('*')`) to handle requests that do not match any other defined routes, typically for 404 responses. ```typescript router .get('/', () => 'home') .all('*', () => error(404)) // Catch everything else ``` -------------------------------- ### Chaining Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/routers.md Demonstrates how to chain multiple HTTP method handlers to a router instance for sequential route definition. ```APIDOC ## Chaining All router HTTP method handlers return the router instance, allowing method chaining: ```typescript router .get('/a', () => 'a') .post('/b', () => 'b') .put('/c', () => 'c') ``` ``` -------------------------------- ### Register GET Route Handler Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/routers.md Register a handler for GET requests to a specific path. Extracts named parameters from the path. ```typescript router.get('/users/:id', (request) => ({ id: request.params.id })) ``` -------------------------------- ### Basic Router Initialization Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/configuration.md Initialize a router with custom options for base path, middleware, error handling, and final middleware. ```typescript import { Router, withParams, error } from 'itty-router' const router = Router({ base: '/api/v1', before: [withParams], catch: error, finally: [] }) ``` -------------------------------- ### Configure Router with Middleware Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/INDEX.md Set up a Router instance with an array of middleware functions for the 'before' hook, and define handlers for 'catch' and 'finally' hooks. Middleware like withParams, withContent, and withCookies can be included. ```typescript import { Router, withParams, withContent, withCookies } from 'itty-router' const router = Router({ before: [withParams, withContent, withCookies], catch: (err) => error(err), finally: [(response) => { /* modify */ return response }] }) ``` -------------------------------- ### ResponseInit Options Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/response-formatters.md Details the use of `ResponseInit` options when calling formatters, including how to set the status code, status text, and headers for the response. It also notes that the content-type header is managed by the formatter. ```APIDOC ## ResponseInit Options When calling formatters with options: ```typescript const response = json({ data: 'value' }, { status: 201, headers: { 'X-Custom': 'value' } }) ``` **Common ResponseInit fields:** | Field | Type | Description | |-------|------|-------------| | status | number | HTTP status code (default 200) | | statusText | string | HTTP status text | | headers | HeadersInit | HTTP headers | **Note:** The content-type header is automatically set by formatters and should not be manually overridden in options. ``` -------------------------------- ### Create Full-Featured Router Instance Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/INDEX.md Instantiate the full-featured Router, which supports lifecycle hooks like 'before', 'catch', and 'finally'. You can provide custom middleware and error handlers during instantiation. ```typescript import { Router } from 'itty-router' const router = Router({ before: [], catch: error, finally: [] }) ``` -------------------------------- ### Hook Execution Order Visualization Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/middleware.md Illustrates the sequence of middleware and route handler execution within an Itty Router, including request matching, error handling, and response finalization. ```text Request ↓ [before] → (early return? → Response) ↓ [match routes] → (no match? → continues to finally) ↓ [route handlers] → (has response? → to finally) ↓ [error?] → (yes? → catch handler → to finally) ↓ [finally] → (transform response) ↓ Response ``` -------------------------------- ### Browser Behavior: Using Credentials Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/cors.md Details how to handle requests with credentials (e.g., cookies) using `fetch` and the necessary server-side `Access-Control-Allow-Credentials: true` header. ```APIDOC **Using Credentials:** ```javascript // JavaScript fetch with credentials fetch(url, { credentials: 'include' // Send cookies }) ``` Server must allow credentials: ``` Access-Control-Allow-Credentials: true ``` ``` -------------------------------- ### Initialize Router with Pre-populated Routes Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/configuration.md Initialize a router with an array of existing route entries. This is an alternative to adding routes via method calls. ```typescript const routes = [ ['GET', /^\/users$/i, [handlerFn], '/users'] ] const router = Router({ routes }) ``` ```typescript const router = Router() router.get('/users', handlerFn) // Typical approach ``` -------------------------------- ### AutoRouter Default Error Handling Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/error-handling.md AutoRouter includes a default error handling mechanism automatically, simplifying setup for common use cases. ```typescript AutoRouter() // Has catch: error automatically ``` -------------------------------- ### Initialize IttyRouter with Options Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/configuration.md Configure the router with options such as a base path prefix or pre-populated routes. The base path is useful for API versioning or grouping. ```typescript const router = IttyRouter({ base: '/api', routes: [] // Can pre-populate }) router.get('/users', () => []) ``` -------------------------------- ### Route Type Definition Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/types.md Defines the function type for HTTP method handlers (e.g., get, post). It accepts a path and an array of request handlers. ```typescript type Route = any[]> = < RequestType = R, Args extends Array = A, >( path: string, ...handlers: RequestHandler[] ) => IttyRouterType ``` -------------------------------- ### Extracting Path Parameters Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/quick-start.md Demonstrates how to extract values from different types of URL path parameters, including single, multiple, and greedy parameters. ```typescript router.get('/users/:userId', ({ userId }) => { return { userId } }) router.get('/users/:userId/posts/:postId', ({ userId, postId }) => { return { userId, postId } }) router.get('/files/:filepath+', ({ filepath }) => { // Greedy param captures multiple segments return { filepath } // "a/b/c/d" }) ``` -------------------------------- ### Default Error Propagation (No Catch Handler) Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/error-handling.md When no `catch` handler is configured, errors thrown within route handlers will propagate to the caller. This example shows an uncaught error. ```typescript const router = Router() // No catch handler router.get('/boom', () => { throw new Error('Uncaught!') // Will propagate to caller }) ``` -------------------------------- ### Apply ResponseInit Options to Formatters Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/response-formatters.md When calling formatters, you can provide `ResponseInit` options to customize the response. This includes setting the status code and headers. ```typescript const response = json({ data: 'value' }, { status: 201, headers: { 'X-Custom': 'value' } }) ``` -------------------------------- ### Chaining Formatters Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/response-formatters.md Demonstrates how to chain multiple response formatters sequentially using the `finally` array in the router configuration. The order of formatters in the `finally` array is crucial for the correct application of transformations. ```APIDOC ## Multiple Formatters Chain formatters in the `finally` array to apply transformations sequentially: ```typescript const addTimestamp = (response, request) => { response.headers.set('X-Response-Time', Date.now()) return response } const router = Router({ finally: [json, addTimestamp] }) ``` **Order matters:** ```typescript // Good: json formats response first, then headers added Router({ finally: [json, addHeaders] }) // Not recommended: headers added before content-type Router({ finally: [addHeaders, json] }) ``` ``` -------------------------------- ### Route Pattern Matching Styles Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/quick-start.md Illustrates various route pattern styles supported by the router, including exact paths, wildcards, parameters, greedy parameters, and combinations. ```typescript router.get('/exact', () => 'exact') router.get('/prefix/*', () => 'wildcard') router.get('/items/:id', () => 'param') router.get('/files/:path+', () => 'greedy') router.get('/:version/api/*', () => 'combination') ``` -------------------------------- ### Creating StatusError Instances Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/error-handling.md Demonstrates how to create StatusError instances with different levels of detail, including just a status code, a status code with a string message, or a status code with a structured object body. ```typescript import { StatusError } from 'itty-router' // Simple error with just status throw new StatusError(404) // With message throw new StatusError(401, 'Unauthorized') // With object body throw new StatusError(400, { error: 'Invalid Request', field: 'email', reason: 'Email is required' }) ``` -------------------------------- ### Define Custom Error Classes Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/error-handling.md Create custom error classes that extend `StatusError` to represent domain-specific errors with associated HTTP status codes and details. This example defines `NotFoundError` and `ValidationError`. ```typescript class NotFoundError extends StatusError { constructor(resource, id) { super(404, { error: `${resource} not found`, id }) } } class ValidationError extends StatusError { constructor(field, reason) { super(400, { error: 'Validation failed', field, reason }) } } const router = Router({ catch: (err) => error(err) }) router.get('/users/:id', ({ id }) => { if (!id) throw new ValidationError('id', 'Required') const user = getUser(id) if (!user) throw new NotFoundError('User', id) return user }) ``` -------------------------------- ### IttyRouter Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/routers.md Creates a lightweight router instance with minimal overhead. It does not include error handling hooks and requires manual handling of unmatched routes and propagating exceptions. ```APIDOC ## IttyRouter A lightweight router without error handling hooks. Minimal overhead for simple use cases. **Module:** `itty-router` or `itty-router/IttyRouter` **Signature:** ```typescript function IttyRouter(options?: IttyRouterOptions): IttyRouterType ``` **Parameters:** | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | IttyRouterOptions | No | {} | Configuration object | | options.base | string | No | '' | Base path prefix for all routes | | options.routes | RouteEntry[] | No | [] | Pre-populated routes array | **Returns:** `IttyRouterType` — A lightweight router instance with HTTP method handlers and fetch method. **Methods:** Identical to Router (get, post, put, patch, delete, head, options, all, fetch) **Differences from Router:** - No `before`, `catch`, or `finally` hooks - Simpler implementation with smaller bundle size - Returns undefined if no route matches (caller must handle) - Exceptions propagate directly (no error handler) **Usage Example:** ```typescript import { IttyRouter } from 'itty-router' const router = IttyRouter() router.get('/:name', ({ params }) => `Hello, ${params.name}!`) export default router ``` **Source:** `src/IttyRouter.ts` ``` -------------------------------- ### AutoRouter Initialization with Custom Options Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/configuration.md Initialize an AutoRouter with extended options, overriding default response formatting and providing custom handlers for missing routes and middleware. ```typescript import { AutoRouter, text, error } from 'itty-router' const router = AutoRouter({ base: '/api', format: text, // Override default JSON format missing: (request) => error(410, 'Gone'), before: [withAuth], catch: customErrorHandler }) ``` -------------------------------- ### Chaining Router HTTP Method Handlers Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/routers.md Demonstrates method chaining for defining multiple HTTP routes on a router instance. This allows for a concise way to register several routes. ```typescript router .get('/a', () => 'a') .post('/b', () => 'b') .put('/c', () => 'c') ``` -------------------------------- ### API Server with Authentication Middleware Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/INDEX.md Demonstrates securing routes with an authentication middleware. The `requireAuth` function checks for an 'authorization' header and returns a 401 error if missing. Uses `withParams` middleware and `error` for catch-all error handling. ```typescript import { Router, error, json, withParams } from 'itty-router' const requireAuth = (request) => { if (!request.headers.get('authorization')) { return error(401) } } const router = Router({ before: [withParams], catch: error, finally: [json] }) router.get('/secure', requireAuth, ({ user }) => ({ data: 'secret' })) ``` -------------------------------- ### Usage Example: Detailed Error Handling Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/error-handling.md Implement a comprehensive error handler that logs errors and handles specific error types like `ValidationError` and `AuthError` before falling back to a default internal server error response. ```typescript const router = Router({ catch: (err, request) => { // Log errors console.error(`${request.method} ${request.url} threw:`, err.message) // Handle different error types if (err instanceof ValidationError) { return error(422, err.message) } if (err instanceof AuthError) { return error(401, 'Unauthorized') } // Default error response return error(500, 'Internal Server Error') } }) ``` -------------------------------- ### Extending Request Type for Application Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/types.md Provides an example of creating application-specific types by extending the base IRequest type. This allows for adding custom properties like user data, database connections, and cache instances to the request object. ```typescript import { IRequest, Router } from 'itty-router' // Extend request with app properties type AppRequest = IRequest & { user: { id: string; name: string } db: Database cache: Cache } // Create typed router const createAppRouter = (db: Database, cache: Cache) => { return Router({ before: [ (request: AppRequest) => { request.db = db request.cache = cache } ] }) } // Use with proper typing const router = createAppRouter(db, cache) ``` -------------------------------- ### Fast vs. Slow Middleware Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/configuration.md Illustrates the difference between efficient, non-blocking middleware and inefficient, blocking middleware. ```typescript // Good: Fast middleware const fastAuth = (request) => { const token = request.headers.get('Authorization') if (!token) return error(401) } ``` ```typescript // Bad: Slow middleware (blocking I/O) const slowAuth = async (request) => { const user = await database.getUser(...) // Blocks! } ``` -------------------------------- ### Generated Documentation Structure Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/MANIFEST.md This snippet shows the directory structure of the generated documentation files for the itty-router project. ```tree /workspace/home/output/ ├── INDEX.md # Master index and quick reference ├── README.md # Project overview ├── MANIFEST.md # This file ├── quick-start.md # Common patterns and usage ├── types.md # Complete type reference ├── configuration.md # Router options and setup └── api-reference/ ├── routers.md # Router implementations ├── middleware.md # Middleware system ├── response-formatters.md # Response utilities ├── error-handling.md # Error management └── cors.md # CORS configuration ``` -------------------------------- ### Configure Global Error Handler Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/error-handling.md Set up a global error handler during Router initialization using the `catch` hook. This function receives the error, request, and any additional arguments. ```typescript Router({ catch: (err, request, ...args) => { // Handle error return error(err) } }) ``` -------------------------------- ### CORS Configuration Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/INDEX.md Shows how to configure Cross-Origin Resource Sharing (CORS) using the `cors` helper. Use `preflight` in `before` handlers and `corsify` in `finally` handlers. ```typescript import { cors } from 'itty-router' const { preflight, corsify } = cors({ origin: 'https://example.com', allowMethods: ['GET', 'POST'], credentials: true }) Router({ before: [preflight], finally: [corsify] }) ``` -------------------------------- ### Security Considerations: Avoid Wildcard + Credentials Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/cors.md Security advice against using a wildcard origin ('*') when credentials are required, as this combination is insecure and not permitted. Explicitly specify allowed origins. ```APIDOC ## Security Considerations ### Avoid Wildcard + Credentials This combination is insecure and not allowed: ```typescript // INVALID - will not work cors({ origin: '*', credentials: true }) // The router will fall back to using request origin instead // Better: specify allowed origins explicitly cors({ origin: ['https://trusted1.com', 'https://trusted2.com'], credentials: true }) ``` ``` -------------------------------- ### Returning Different Response Formats Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/quick-start.md Shows how to return various response types directly from handlers, including JSON, plain text, HTML, empty responses (204), and redirects (301). ```typescript import { json, text, html, status } from 'itty-router' router.get('/json', () => ({ key: 'value' })) // Auto-formatted router.get('/text', () => 'plain text') // Auto-formatted router.get('/html', () => '

Hello

') // Auto-formatted router.get('/empty', () => status(204)) // No content router.get('/redirect', () => status(301, { headers: { 'Location': 'https://example.com' } })) ``` -------------------------------- ### Initialize CORS Middleware Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/cors.md Create CORS middleware with configurable origin policies and header handling. The `preflight` function should be used in a `before` handler and `corsify` in a `finally` handler. ```typescript import { Router, cors, json } from 'itty-router' const { preflight, corsify } = cors({ origin: 'https://example.com', allowMethods: ['GET', 'POST', 'PUT'], credentials: true }) const router = Router({ before: [preflight], finally: [corsify, json] }) router .get('/api/data', () => ({ data: 'value' })) .post('/api/data', () => ({ created: true })) export default router ``` -------------------------------- ### Create IttyRouter Instance Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/INDEX.md Instantiate the lightweight IttyRouter for basic routing needs. This version does not include built-in error handling hooks. ```typescript import { IttyRouter } from 'itty-router' const router = IttyRouter() ``` -------------------------------- ### Custom Formatters Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/response-formatters.md Explains how to create custom response formatters for any content type using the `createResponse` helper function. This allows for flexible response formatting beyond the built-in options. ```APIDOC ## Custom Formatters Create formatters for any content type: ```typescript import { createResponse } from 'itty-router' const yaml = createResponse('application/yaml', (data) => { // Convert to YAML string return yamlStringify(data) }) const markdown = createResponse('text/markdown; charset=utf-8', (data) => { // Convert to Markdown return markdownify(data) }) const router = Router({ finally: [yaml] // Use custom formatter }) router.get('/config', () => ({ name: 'app', version: '1.0.0' })) // Response: Content-Type: application/yaml // name: app // version: 1.0.0 ``` ``` -------------------------------- ### Preflight Requests Handling Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/api-reference/cors.md Automatically handle OPTIONS requests for preflight checks. The `preflight` function returns a 204 No Content response for OPTIONS requests, sets CORS headers, and passes through non-OPTIONS requests. ```APIDOC ## Preflight Requests Handle OPTIONS requests automatically. **Function Signature:** ```typescript type Preflight = (request: IRequest) => Response | void ``` The `preflight` function: - Returns a 204 No Content response for OPTIONS requests - Sets all CORS headers based on configuration - Returns undefined for non-OPTIONS requests (pass through) **Usage:** ```typescript const { preflight, corsify } = cors(options) const router = Router({ before: [preflight] // Handle preflight requests }) ``` **Preflight Response Example:** Request: ``` OPTIONS /api/data HTTP/1.1 Origin: https://example.com Access-Control-Request-Method: POST Access-Control-Request-Headers: Content-Type ``` Response: ``` 204 No Content Access-Control-Allow-Origin: https://example.com Access-Control-Allow-Methods: GET,POST,PUT,DELETE Access-Control-Allow-Headers: Content-Type Access-Control-Max-Age: 86400 ``` ``` -------------------------------- ### Response Formatters Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/INDEX.md Demonstrates various response formatters like json, text, html, status, and image types. Use these with a `finally` handler to format the response body. ```typescript import { json, text, html, status, jpeg, png, webp } from 'itty-router' router.get('/json', () => ({ data: 'value' })) // Use with finally: [json] router.get('/text', () => 'text content') // Use with finally: [text] router.get('/html', () => '

HTML

') // Use with finally: [html] router.get('/empty', () => status(204)) router.get('/image', () => imageBuffer) // Use with finally: [jpeg/png/webp] ``` -------------------------------- ### Configure Router Based on Environment Source: https://github.com/kwhitley/itty-router/blob/v5.x/_autodocs/configuration.md Adapt router configuration, including middleware and error handling, based on environment variables like NODE_ENV. This allows for different behavior in development and production. ```typescript const isDev = process.env.NODE_ENV === 'development' const isProd = process.env.NODE_ENV === 'production' const router = Router({ before: [ withParams, isDev ? withDetailedDebug : undefined ].filter(Boolean), catch: (err, request) => { if (isDev) { return error(err.status || 500, { message: err.message, stack: err.stack }) } return error(err.status || 500, { error: 'Server error' }) }, finally: [ isProd ? addSecurityHeaders : undefined, json, addMetrics ].filter(Boolean) }) ```