๐ŸŒ CORS Middleware

Cross-Origin Resource Sharing

This example shows how to enable CORS for specific origins using createCORS(). It handles both standard and preflight requests for secure and compliant cross-origin API access.

Whitelist trusted domains, enable credentials, and allow required headers and methods.

๐Ÿ”ง Example Code

import type { Route } from "tirne";
import { Server,createCORS,json } from "tirne";

const cors = createCORS({
  origin: ["https://example.com", "https://admin.example.com"],
  credentials: true,
  headers: ["Content-Type", "Authorization"],
  methods: ["GET", "POST"],
  maxAge: 86400, // cache preflight for 1 day
});

const routes: Route[] = [
  {
    method: "GET",
    path: "/data",
    handler: () => json({ message: "Hello with CORS" }),
  },
];

const server = new Server(routes);
server.use(cors); // global middleware

export default {
  fetch: (req: Request) => server.fetch(req),
};

๐Ÿงช Functionality Check

Test CORS behavior with the following curl commands:

1. โœ… Simple Request from Allowed Origin

curl -i -H "Origin: https://example.com" http://localhost:3000/data
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Credentials: true
Content-Type: application/json

{"message":"Hello with CORS"}

2. โœ… Preflight Request (OPTIONS)

curl -i -X OPTIONS http://localhost:3000/data \
  -H "Origin: https://example.com" \
  -H "Access-Control-Request-Method: POST"
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET,POST
Access-Control-Allow-Headers: Content-Type,Authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400