CORS

Cross-Origin Resource Sharing (CORS) is a security mechanism that allows a web page from one domain or Origin to access a resource with a different domain. Harpia provides a robust, built-in CORS configuration out of the box.

Basic Usage

You can enable CORS with default settings (allowing all origins) simply by calling app.cors() before starting the server.

import harpia from "@harpiats/core";

const app = harpia();

// Enable CORS with default settings (Allows all origins)
app.cors();

app.get("/data", (req, res) => {
  res.json({ message: "This data is accessible from anywhere!" });
});

Configuration Options

You can pass a configuration object to app.cors() to fine-tune the behavior. If you prefer, you can import the CorsOptions type from @harpiats/core to strictly type this object.

import type { CorsOptions } from "@harpiats/core";

const corsConfig: CorsOptions = {
  origin: "https://my-frontend.com",
  methods: ["GET", "POST", "PUT"],
  credentials: true,
  maxAge: 86400, // 24 hours
};

app.cors(corsConfig);

origin

Configures the Access-Control-Allow-Origin CORS header. It accepts multiple formats:

  • boolean: true sets the origin to * (allow all). false disables CORS.
  • string: A specific origin (e.g., "http://localhost:3000").
  • RegExp: A regular expression to match origins (e.g., /^https:\/\/.*\.my-domain\.com$/).
  • Array: An array of strings or regular expressions.
  • Function: A custom validation function.

Custom Validation Function

You can use a function to perform asynchronous or complex origin validation (e.g., checking a database).

app.cors({
  origin: (requestOrigin, callback) => {
    const allowedList = ["https://site-a.com", "https://site-b.com"];
    
    if (allowedList.includes(requestOrigin)) {
      // Allow the origin
      callback(null, requestOrigin);
    } else {
      // Deny
      callback(new Error("Origin not allowed"));
    }
  }
});

methods

Configures the Access-Control-Allow-Methods header. Can be a single string like "GET,POST" or an array of HTTP methods like ["GET", "POST", "DELETE"].

allowedHeaders

Configures the Access-Control-Allow-Headers header. Specifies which headers can be used during the actual request. Can be a string or an array of strings.

exposedHeaders

Configures the Access-Control-Expose-Headers header. Specifies headers that browsers are allowed to access in the response. Can be a string or an array of strings.

credentials

Set to true to pass the Access-Control-Allow-Credentials header, allowing the client to send cookies and authorization headers with cross-origin requests.

maxAge

Configures the Access-Control-Max-Age header (in seconds), indicating how long the results of a preflight request can be cached.

Preflight Requests (OPTIONS)

Harpia automatically handles OPTIONS preflight requests for CORS.

  • optionsSuccessStatus: Provides a status code to use for successful OPTIONS requests (defaults to 204).
  • preflightContinue: If true, the framework will pass the OPTIONS request to the next route/middleware handler instead of automatically terminating it.