CORS
Features
Section titled “Features”- Easy setup for Cross-Origin Resource Sharing (CORS).
- Global or route-specific middleware support.
- Handles preflight requests automatically.
Installation
Section titled “Installation”you need to install the following packages
npm install @gaman/cors
pnpm install @gaman/cors
yarn install @gaman/cors
bun install @gaman/cors
-
Global Middleware
Apply the CORS middleware globally to all routes:
example.block.ts export default defineBlock({includes: [cors({ origin: "*" })], // Global CORS middleware}); -
Route-Specific Middleware
Apply CORS middleware only to specific routes:
example.routes.ts export default defineRoutes(() => ({"/public": async (ctx) => {return Res.json({ message: "No CORS restrictions here!" });},"/private/*": cors({ origin: ["https://example.com"] }), // Specific middleware"/private/data": async (ctx) => {return Res.json({ message: "Restricted to example.com" });},}));
Configuration Options
Section titled “Configuration Options”Customize CORS behavior using these options:
Option | Type | Description | Default |
---|---|---|---|
origin | string, string[], null | Allowed origin(s) for the request. | * (all origins) |
allowMethods | string[] | HTTP methods allowed for the request. | ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"] |
allowHeaders | string[] | Headers allowed in the request. | ["Content-Type", "Authorization"] |
maxAge | number | Maximum cache age for preflight requests (in seconds). | undefined |
credentials | boolean | Include credentials (cookies, HTTP auth) in the request. | false |
exposeHeaders | string[] | Headers exposed to the client in the response. | undefined |
Examples
Section titled “Examples”CORS with Credentials
Section titled “CORS with Credentials”export default defineBlock({ includes: [ cors({ origin: "https://mywebsite.com", credentials: true, }), ],});
Custom Headers and Methods
Section titled “Custom Headers and Methods”export default defineBlock({ includes: [ cors({ origin: "*", allowMethods: ["GET", "POST"], allowHeaders: ["X-Custom-Header", "Authorization"], maxAge: 86400, // Cache for 1 day }), ],});
- Use
origin
with a list of domains to restrict access to specific origins. - Set
maxAge
to improve performance by reducing preflight requests.
Q: What is CORS?
Section titled “Q: What is CORS?”CORS stands for Cross-Origin Resource Sharing, a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the resource originated.
Q: Why use this middleware?
Section titled “Q: Why use this middleware?”The middleware simplifies setting up CORS policies, reducing the need for repetitive boilerplate code.
Empower your GamanJS applications with robust CORS policies!