### Install and Configure @adonisjs/cors Source: https://context7.com/adonisjs/cors/llms.txt Run this command once to scaffold the config file, register the provider, and add the middleware to your server stack. ```bash node ace configure @adonisjs/cors ``` -------------------------------- ### Automated Setup with `node ace configure` Source: https://context7.com/adonisjs/cors/llms.txt This command scaffolds the configuration file, registers the provider, and adds the middleware to the server middleware stack automatically. ```APIDOC ## Installation & Automated Setup `configure` — scaffold config file, register provider and server middleware in one command. Running `node ace configure @adonisjs/cors` calls the exported `configure` function, which uses AdonisJS codemods to create `config/cors.ts`, add `@adonisjs/cors/cors_provider` to `adonisrc.ts`, and insert `@adonisjs/cors/cors_middleware` into the server middleware stack. ```ts // Run once in your AdonisJS project: // node ace configure @adonisjs/cors // // This produces the following mutations automatically: // 1. config/cors.ts (new file) import { defineConfig } from '@adonisjs/cors' const corsConfig = defineConfig({ enabled: true, origin: true, methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'], headers: true, exposeHeaders: [], credentials: true, maxAge: 90, }) export default corsConfig // 2. adonisrc.ts (appended by codemod) // providers: [() => import('@adonisjs/cors/cors_provider')] // 3. start/kernel.ts (appended by codemod) // server.use([() => import('@adonisjs/cors/cors_middleware')]) ``` ``` -------------------------------- ### CORS Middleware Scenarios Source: https://context7.com/adonisjs/cors/llms.txt Illustrates the response headers and behavior for different CORS request scenarios, including allowed origins, preflight requests, disallowed origins, and wildcard origin with credentials. ```text // ── What the middleware emits for different scenarios ────────────────────── // Scenario A: Simple GET from an allowed origin // Request headers: Origin: https://app.example.com // Response headers: Access-Control-Allow-Origin: https://app.example.com // Access-Control-Allow-Credentials: true // (next() IS called — response body flows through) // Scenario B: Preflight OPTIONS from an allowed origin // Request headers: Origin: https://app.example.com // Access-Control-Request-Method: POST // Access-Control-Request-Headers: Authorization // Response headers: Access-Control-Allow-Origin: https://app.example.com // Access-Control-Allow-Credentials: true // Access-Control-Allow-Methods: GET,HEAD,POST,PUT,DELETE // Access-Control-Allow-Headers: authorization // Access-Control-Max-Age: 90 // HTTP Status: 204 (next() is NOT called) // Scenario C: Request from a disallowed origin // Request headers: Origin: https://attacker.example.com // Response headers: (none — no CORS headers set) // (for OPTIONS: 204 with no CORS headers; next() not called) // (for GET/POST: next() IS called, no CORS headers) // Scenario D: Wildcard origin with credentials=true // Config: origin: '*', credentials: true // Result: Access-Control-Allow-Origin: ← NOT '*' // Access-Control-Allow-Credentials: true // Note: The spec forbids `Allow-Origin: *` + `Allow-Credentials: true`, // so the package automatically substitutes the real origin value. ``` -------------------------------- ### Allow Any Origin with Wildcard and No Credentials Source: https://context7.com/adonisjs/cors/llms.txt Use a wildcard '*' for the origin to allow any origin, but ensure credentials are not sent. Note the interaction between wildcard origins and credentials. ```typescript import { defineConfig } from '@adonisjs/cors' // 3. Wildcard — allows any origin, but note credentials interaction export default defineConfig({ origin: '*', credentials: false }) // → Access-Control-Allow-Origin: * ``` -------------------------------- ### Instantiate CorsMiddleware Manually Source: https://context7.com/adonisjs/cors/llms.txt Instantiate the middleware directly with a config object. Useful in tests or standalone HTTP servers. ```typescript import CorsMiddleware from '@adonisjs/cors/cors_middleware' import { defineConfig } from '@adonisjs/cors' // Manual construction (useful in tests or standalone HTTP servers) const cors = new CorsMiddleware( defineConfig({ origin: ['http://localhost:3000'], methods: ['GET', 'POST'], credentials: false, maxAge: 90, }) ) // Use in a raw Node.js HTTP server import { createServer } from 'node:http' import { RequestFactory, ResponseFactory, HttpContextFactory } from '@adonisjs/core/factories/http' const server = createServer(async (req, res) => { const request = new RequestFactory().merge({ req, res }).create() const response = new ResponseFactory().merge({ req, res }).create() const ctx = new HttpContextFactory().merge({ request, response }).create() await cors.handle(ctx, async () => { response.send({ hello: 'world' }) }) response.finish() }) server.listen(3333) ``` -------------------------------- ### CorsMiddleware Constructor Source: https://context7.com/adonisjs/cors/llms.txt Instantiate the CorsMiddleware directly with a configuration object. This is useful for testing or custom wiring outside the standard AdonisJS container binding. ```APIDOC ## CorsMiddleware — constructor `new CorsMiddleware(config: CorsConfig)` — instantiate the middleware directly with a config object. Accepts a `CorsConfig` (typically produced by `defineConfig`) and normalises it once at construction time. The instance is stateless and safe to share across all requests. The AdonisJS container binds it automatically when the provider is registered, but it can also be constructed manually for testing or custom wiring. ```ts import CorsMiddleware from '@adonisjs/cors/cors_middleware' import { defineConfig } from '@adonisjs/cors' // Manual construction (useful in tests or standalone HTTP servers) const cors = new CorsMiddleware( defineConfig({ origin: ['http://localhost:3000'], methods: ['GET', 'POST'], credentials: false, maxAge: 90, }) ) // Use in a raw Node.js HTTP server import { createServer } from 'node:http' import { RequestFactory, ResponseFactory, HttpContextFactory } from '@adonisjs/core/factories/http' const server = createServer(async (req, res) => { const request = new RequestFactory().merge({ req, res }).create() const response = new ResponseFactory().merge({ req, res }).create() const ctx = new HttpContextFactory().merge({ request, response }).create() await cors.handle(ctx, async () => { response.send({ hello: 'world' }) }) response.finish() }) server.listen(3333) ``` ``` -------------------------------- ### Default CORS Configuration Source: https://context7.com/adonisjs/cors/llms.txt This is the default configuration file generated by the `configure` command. It sets up basic CORS policies. ```typescript // Run once in your AdonisJS project: // node ace configure @adonisjs/cors // // This produces the following mutations automatically: // 1. config/cors.ts (new file) import { defineConfig } from '@adonisjs/cors' const corsConfig = defineConfig({ enabled: true, origin: true, methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'], headers: true, exposeHeaders: [], credentials: true, maxAge: 90, }) export default corsConfig // 2. adonisrc.ts (appended by codemod) // providers: [() => import('@adonisjs/cors/cors_provider')] // 3. start/kernel.ts (appended by codemod) // server.use([() => import('@adonisjs/cors/cors_middleware')]) ``` -------------------------------- ### Dynamic CORS Configuration with Callbacks Source: https://context7.com/adonisjs/cors/llms.txt Use callbacks for dynamic CORS policies based on request context. This allows for per-request origin validation or disabling CORS for specific routes. ```typescript import type { CorsConfig } from '@adonisjs/cors/types' import type { HttpContext } from '@adonisjs/core/http' const config: CorsConfig = { // Disable CORS entirely for internal health-check routes enabled: (ctx: HttpContext) => !ctx.request.url().startsWith('/health'), // Dynamic per-request origin allowlist driven by a database lookup origin: async (requestOrigin: string, ctx: HttpContext) => { const allowed = await ctx.container.make('TenantService').getAllowedOrigins() return allowed.includes(requestOrigin) ? requestOrigin : false }, methods: ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'], // Mirror back whatever headers the client requests (permissive dev mode) headers: true, // Expose custom headers that browser JS needs to read exposeHeaders: ['X-RateLimit-Remaining', 'X-Request-Id'], credentials: true, maxAge: 90, } ``` -------------------------------- ### Allow Specific Headers with a Comma-Separated String Source: https://context7.com/adonisjs/cors/llms.txt Configure allowed headers using a single comma-separated string. This is a concise method for specifying multiple permitted headers. ```typescript import { defineConfig } from '@adonisjs/cors' // 4. Comma-separated string export default defineConfig({ headers: 'Content-Type,Authorization' }) ``` -------------------------------- ### Using `defineConfig` for CORS Configuration Source: https://context7.com/adonisjs/cors/llms.txt The `defineConfig` function merges supplied partial configuration with built-in defaults to create a fully-resolved CORS configuration object. It can be imported from the package root `@adonisjs/cors`. ```APIDOC ## defineConfig `defineConfig(config: Partial): CorsConfig` — create a fully-resolved CORS configuration with defaults applied. Merges the supplied partial config over the built-in defaults (`enabled: true`, `origin: true`, `methods: ['GET','HEAD','POST','PUT','DELETE']`, `headers: true`, `exposeHeaders: []`, `credentials: true`, `maxAge: 90`) and returns a complete `CorsConfig` object. Import from the package root `@adonisjs/cors`. ```ts // config/cors.ts import { defineConfig } from '@adonisjs/cors' export default defineConfig({ // Allow requests only from these two origins (case-sensitive match) origin: ['https://app.example.com', 'https://admin.example.com'], // Restrict to safe methods only methods: ['GET', 'HEAD', 'POST'], // Only accept these custom headers in preflight headers: ['Content-Type', 'Authorization', 'X-Request-Id'], // Expose a custom timing header to browser JS exposeHeaders: ['X-Response-Time'], // Allow cookies / Authorization headers to be sent cross-origin credentials: true, // Cache preflight for 10 minutes maxAge: 600, }) // Returns: // { // enabled: true, // origin: ['https://app.example.com', 'https://admin.example.com'], // methods: ['GET', 'HEAD', 'POST'], // headers: ['Content-Type', 'Authorization', 'X-Request-Id'], // exposeHeaders: ['x-response-time'], ← lower-cased internally // credentials: true, // maxAge: 600, // } ``` ``` -------------------------------- ### Register CorsMiddleware as Global Middleware Source: https://context7.com/adonisjs/cors/llms.txt Register the CORS middleware in start/kernel.ts to apply it globally to all server requests. This is often done automatically by the configure function. ```typescript // start/kernel.ts — register as a global server middleware (done automatically by configure) import server from '@adonisjs/core/services/server' server.use([ () => import('@adonisjs/cors/cors_middleware'), // ... other global middleware ]) ``` -------------------------------- ### Dynamic Origin Control with a Callback Source: https://context7.com/adonisjs/cors/llms.txt Implement dynamic CORS origin control using a callback function. This allows you to determine allowed origins at runtime based on request details, such as subdomains. ```typescript import { defineConfig } from '@adonisjs/cors' // 6. Runtime callback — look up allowed origins per request export default defineConfig({ origin: (requestOrigin, ctx) => { const subdomain = requestOrigin.replace('https://', '').split('.')[0] const allowedSubdomains = ['app', 'admin', 'api'] return allowedSubdomains.includes(subdomain) ? requestOrigin : false }, }) // Note: origin matching is always CASE-SENSITIVE // 'foo.com' ≠ 'FOO.com' ``` -------------------------------- ### CorsMiddleware Handle Method Source: https://context7.com/adonisjs/cors/llms.txt Process a single HTTP request through the CORS policy. This method handles setting appropriate CORS headers based on the request origin and configuration, and determines whether to call the next middleware in the chain. ```APIDOC ## CorsMiddleware — handle `handle(ctx: HttpContext, next: NextFn): Promise` — process a single HTTP request through the CORS policy. This is the standard AdonisJS middleware signature. For requests without an `Origin` header or when CORS is disabled, `next()` is called immediately with no header mutations. For simple (non-`OPTIONS`) cross-origin requests, the method sets `Access-Control-Allow-Origin`, optionally `Access-Control-Allow-Credentials`, and `Access-Control-Expose-Headers`, then calls `next()`. For preflight `OPTIONS` requests it sets the full preflight response headers and terminates the request with `204 No Content` without calling `next()`. ```ts // start/kernel.ts — register as a global server middleware (done automatically by configure) import server from '@adonisjs/core/services/server' server.use([ () => import('@adonisjs/cors/cors_middleware'), // ... other global middleware ]) // ── What the middleware emits for different scenarios ────────────────────── // Scenario A: Simple GET from an allowed origin // Request headers: Origin: https://app.example.com // Response headers: Access-Control-Allow-Origin: https://app.example.com // Access-Control-Allow-Credentials: true // (next() IS called — response body flows through) // Scenario B: Preflight OPTIONS from an allowed origin // Request headers: Origin: https://app.example.com // Access-Control-Request-Method: POST // Access-Control-Request-Headers: Authorization // Response headers: Access-Control-Allow-Origin: https://app.example.com // Access-Control-Allow-Credentials: true // Access-Control-Allow-Methods: GET,HEAD,POST,PUT,DELETE // Access-Control-Allow-Headers: authorization // Access-Control-Max-Age: 90 // HTTP Status: 204 (next() is NOT called) // Scenario C: Request from a disallowed origin // Request headers: Origin: https://attacker.example.com // Response headers: (none — no CORS headers set) // (for OPTIONS: 204 with no CORS headers; next() not called) // (for GET/POST: next() IS called, no CORS headers) // Scenario D: Wildcard origin with credentials=true // Config: origin: '*', credentials: true // Result: Access-Control-Allow-Origin: ← NOT '*' // Access-Control-Allow-Credentials: true // Note: The spec forbids `Allow-Origin: *` + `Allow-Credentials: true`, // so the package automatically substitutes the real origin value. ``` ``` -------------------------------- ### Customizing CORS Configuration Source: https://context7.com/adonisjs/cors/llms.txt Configure specific origins, methods, headers, and other CORS options. Note that `exposeHeaders` are lower-cased internally. ```typescript // config/cors.ts import { defineConfig } from '@adonisjs/cors' export default defineConfig({ // Allow requests only from these two origins (case-sensitive match) origin: ['https://app.example.com', 'https://admin.example.com'], // Restrict to safe methods only methods: ['GET', 'HEAD', 'POST'], // Only accept these custom headers in preflight headers: ['Content-Type', 'Authorization', 'X-Request-Id'], // Expose a custom timing header to browser JS exposeHeaders: ['X-Response-Time'], // Allow cookies / Authorization headers to be sent cross-origin credentials: true, // Cache preflight for 10 minutes maxAge: 600, }) // Returns: // { // enabled: true, // origin: ['https://app.example.com', 'https://admin.example.com'], // methods: ['GET', 'HEAD', 'POST'], // headers: ['Content-Type', 'Authorization', 'X-Request-Id'], // exposeHeaders: ['x-response-time'], ← lower-cased internally // credentials: true, // maxAge: 600, // } ``` -------------------------------- ### Dynamic Header Control with a Callback Source: https://context7.com/adonisjs/cors/llms.txt Implement dynamic CORS header control using a callback function. This allows runtime inspection of requested headers to permit or deny them based on custom logic, such as excluding sensitive headers. ```typescript import { defineConfig } from '@adonisjs/cors' // 5. Callback — inspect the requested headers at runtime export default defineConfig({ headers: (requestedHeaders, ctx) => { // Allow everything except server-side-only headers const forbidden = ['x-internal-token', 'x-admin-bypass'] const safe = requestedHeaders.filter((h) => !forbidden.includes(h.toLowerCase())) return safe.length === requestedHeaders.length ? true : safe }, }) ``` -------------------------------- ### Allow Specific Origins with a Comma-Separated String Source: https://context7.com/adonisjs/cors/llms.txt Configure allowed origins using a single comma-separated string. This provides a concise way to list multiple allowed origins. ```typescript import { defineConfig } from '@adonisjs/cors' // 5. Comma-separated string export default defineConfig({ origin: 'https://app.example.com,https://admin.example.com' }) ``` -------------------------------- ### Reflect All Client Headers Source: https://context7.com/adonisjs/cors/llms.txt Configure CORS to reflect back all headers requested by the client. This is achieved by setting the 'headers' option to true. ```typescript import { defineConfig } from '@adonisjs/cors' // 1. Reflect back whatever headers the client asks for export default defineConfig({ headers: true }) ``` -------------------------------- ### Manually Register CorsProvider in AppProvider Source: https://context7.com/adonisjs/cors/llms.txt Manually register the CorsProvider within your AppProvider if not using the configure command. The provider's register method handles reading the configuration and binding the CorsMiddleware. ```typescript // providers/app_provider.ts import type { ApplicationService } from '@adonisjs/core/types' import CorsProvider from '@adonisjs/cors/cors_provider' export default class AppProvider { constructor(protected app: ApplicationService) {} register() { // The CorsProvider's register() reads config/cors.ts and binds CorsMiddleware new CorsProvider(this.app).register() } } ``` -------------------------------- ### Allow All Origins with CORS Source: https://context7.com/adonisjs/cors/llms.txt Configure CORS to allow requests from any origin. This is often used for development convenience. The Access-Control-Allow-Origin header will reflect the request origin. ```typescript import { defineConfig } from '@adonisjs/cors' // 1. Allow every origin (development convenience) export default defineConfig({ origin: true }) // → Access-Control-Allow-Origin: ``` -------------------------------- ### CorsConfig Type with Dynamic Options Source: https://context7.com/adonisjs/cors/llms.txt The `CorsConfig` type defines all CORS policy options. Each field can accept a static value or a callback function that receives the `HttpContext` for dynamic, per-request configuration. ```APIDOC ## CorsConfig Type `CorsConfig` — the TypeScript interface that describes all CORS policy options. Every field accepts either a static value or a callback receiving the current `HttpContext`, giving full runtime flexibility. Import from `@adonisjs/cors/types`. ```ts import type { CorsConfig } from '@adonisjs/cors/types' import type { HttpContext } from '@adonisjs/core/http' const config: CorsConfig = { // Disable CORS entirely for internal health-check routes enabled: (ctx: HttpContext) => !ctx.request.url().startsWith('/health'), // Dynamic per-request origin allowlist driven by a database lookup origin: async (requestOrigin: string, ctx: HttpContext) => { const allowed = await ctx.container.make('TenantService').getAllowedOrigins() return allowed.includes(requestOrigin) ? requestOrigin : false }, methods: ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'], // Mirror back whatever headers the client requests (permissive dev mode) headers: true, // Expose custom headers that browser JS needs to read exposeHeaders: ['X-RateLimit-Remaining', 'X-Request-Id'], credentials: true, maxAge: 90, } ``` ``` -------------------------------- ### Reject All Custom Headers Source: https://context7.com/adonisjs/cors/llms.txt Configure CORS to reject all custom headers by setting the 'headers' option to false. This ensures only standard headers are processed. ```typescript import { defineConfig } from '@adonisjs/cors' // 2. Reject all custom headers export default defineConfig({ headers: false }) ``` -------------------------------- ### Allow Specific Headers with an Array Source: https://context7.com/adonisjs/cors/llms.txt Define an explicit allowlist of headers that are permitted in CORS requests. Header matching is case-insensitive internally. The output shows the normalized headers. ```typescript import { defineConfig } from '@adonisjs/cors' // 3. Explicit allowlist (case-insensitive matching applied internally) export default defineConfig({ headers: ['Content-Type', 'Authorization', 'X-Request-Id'], }) // Preflight Access-Control-Allow-Headers: content-type,authorization,x-request-id ``` -------------------------------- ### Register CorsProvider in adonisrc.ts Source: https://context7.com/adonisjs/cors/llms.txt Register the CorsProvider automatically managed by the configure command. This provider reads configuration from config/cors.ts. ```typescript // adonisrc.ts (managed automatically by the configure command) import { defineConfig } from '@adonisjs/core' export default defineConfig({ providers: [ // ... core providers () => import('@adonisjs/cors/cors_provider'), ], }) ``` -------------------------------- ### Block All Cross-Origin Requests with CORS Source: https://context7.com/adonisjs/cors/llms.txt Configure CORS to block all cross-origin requests by setting the origin to false. No CORS headers will be set, effectively denying cross-origin access. ```typescript import { defineConfig } from '@adonisjs/cors' // 2. Block all cross-origin requests export default defineConfig({ origin: false }) // → No CORS headers set ``` -------------------------------- ### Allow Specific Origins with an Array Source: https://context7.com/adonisjs/cors/llms.txt Define an explicit array of allowed origins for CORS requests. Only requests originating from these specified URLs will be permitted. ```typescript import { defineConfig } from '@adonisjs/cors' // 4. Explicit array of allowed origins export default defineConfig({ origin: ['https://app.example.com', 'https://admin.example.com'], }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.