Built-in Middlewares

CORS Middleware

Configure Cross-Origin Resource Sharing (CORS) using @taserjs/router/cors with static origins, dynamic domain resolvers, and preflight support.

Taser.js includes a high-performance CORS middleware exported from @taserjs/router/cors that handles origin matching, preflight OPTIONS requests, credentials, and custom headers.


Basic Configuration

Attach CORS to your root layout (src/routes/$.ts) to enable cross-origin requests across your entire API:

src/routes/$.ts
import { cors } from "@taserjs/router/cors";
import { t } from "@taserjs/router";

export default t.layout("/*").use(
  cors({
    origin: ["https://example.com", "https://app.example.com"],
    allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allowHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
    exposeHeaders: ["Content-Length", "X-Request-Id"],
    credentials: true,
    maxAge: 86400,
  }),
);

Dynamic Origin Resolution

If your application supports multiple dynamic domains or customer vanity subdomains, pass a function to origin:

src/routes/$.ts
import { cors } from "@taserjs/router/cors";
import { t } from "@taserjs/router";

export default t.layout("/*").use(
  cors({
    origin: (origin) => {
      // Allow localhost in development:
      if (!origin || origin.includes("localhost")) {
        return origin;
      }

      // Allow any *.example.com subdomain:
      if (origin.endsWith(".example.com")) {
        return origin;
      }

      // Disallow all other origins:
      return null;
    },
    credentials: true,
  }),
);

Prop

Type


Scoped CORS per Route Group

You can apply different CORS policies to different parts of your API by placing the middleware in specific layout files:

src/routes/
├── $.ts                 -> Global layout
├── public.ts            -> cors({ origin: "*" }) for open public API
└── internal.ts          -> cors({ origin: "https://admin.internal" }) for internal dashboard