Skip to content

CORS

  • Easy setup for Cross-Origin Resource Sharing (CORS).
  • Global or route-specific middleware support.
  • Handles preflight requests automatically.

you need to install the following packages

Terminal window
npm install @gaman/cors
  1. Global Middleware

    Apply the CORS middleware globally to all routes:

    example.block.ts
    export default defineBlock({
    includes: [cors({ origin: "*" })], // Global CORS middleware
    });
  2. 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" });
    },
    }));

Customize CORS behavior using these options:

OptionTypeDescriptionDefault
originstring, string[], nullAllowed origin(s) for the request.* (all origins)
allowMethodsstring[]HTTP methods allowed for the request.["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"]
allowHeadersstring[]Headers allowed in the request.["Content-Type", "Authorization"]
maxAgenumberMaximum cache age for preflight requests (in seconds).undefined
credentialsbooleanInclude credentials (cookies, HTTP auth) in the request.false
exposeHeadersstring[]Headers exposed to the client in the response.undefined

example.block.ts
export default defineBlock({
includes: [
cors({
origin: "https://mywebsite.com",
credentials: true,
}),
],
});

example.block.ts
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.

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.

The middleware simplifies setting up CORS policies, reducing the need for repetitive boilerplate code.


Empower your GamanJS applications with robust CORS policies!