Restify CORS Middleware

raw JSON →
1.1.1 verified Thu Apr 23 auth: no javascript

restify-cors-middleware is a library providing W3C-compliant Cross-Origin Resource Sharing (CORS) middleware specifically designed for Restify servers. The current stable version is 1.1.1. This library offers robust control over allowed origins, headers, and preflight requests. Key differentiators include its dynamic handling of `Access-Control-Allow-Origin` by returning the matched origin rather than a simple wildcard, which enhances security. It supports flexible origin specification using strings, wildcards, and regular expressions. The package maintains compatibility with a broad range of Restify versions (2.6.x - 7.x.x) through its peer dependency. While a specific release cadence isn't documented, historical releases show updates addressing security concerns, such as the upgrade to Restify 4.1.x to fix a `negotiator` module vulnerability in version 0.0.7. It is predominantly used in CommonJS environments.

error CORS headers are missing or incorrect for my client requests.
cause The client request might not be sending an `Origin` header, or the `Origin` header sent does not match any of the configured `origins` in the middleware.
fix
Verify that your client-side code sends an Origin header for cross-origin requests. Double-check the origins configuration in corsMiddleware to ensure the client's origin is correctly specified (using exact strings or a matching regular expression).
error My caching layer is serving incorrect CORS headers to different clients.
cause A reverse proxy (like Varnish or a CDN) is caching responses without considering the `Origin` header, leading to an `Access-Control-Allow-Origin` value being served inappropriately to subsequent requests from different origins.
fix
Update your reverse proxy configuration to include Vary: Origin in its caching directives. This instructs the proxy to store separate cached versions for requests originating from different domains.
error Security scanner reports vulnerability in 'negotiator' module or Restify dependency.
cause You are using an older version of `restify-cors-middleware` or `restify` that contains known vulnerabilities in its dependency tree, specifically affecting `negotiator`.
fix
Upgrade restify-cors-middleware to the latest stable version (1.1.1 or newer). Additionally, ensure your restify peer dependency is 4.1.X or higher, as recommended by the restify-cors-middleware documentation since v0.0.7.
breaking Older versions (prior to v0.0.7) of `restify-cors-middleware` might depend on `restify` versions vulnerable to security issues, specifically with the `negotiator` module. This could lead to potential security risks.
fix Upgrade `restify-cors-middleware` to at least v0.0.7 and ensure your `restify` peer dependency is 4.1.X or newer to address known vulnerabilities.
gotcha While `origins: ['*']` is a valid configuration, it comes with significant security implications as it allows requests from any domain. The middleware's internal logic will still return the specific `Origin` from the request, but this does not mitigate the fundamental risk of an open CORS policy.
fix Specify the exact list of allowed origins (strings or regular expressions) to limit cross-origin access to trusted domains only. Avoid `origins: ['*']` unless absolutely necessary and understood.
gotcha Requests that do not include an `Origin` header (e.g., direct requests from the same origin, cURL requests without `-H 'Origin:...'`) will not receive any CORS-related response headers, as per the W3C spec. This can be a source of confusion during testing or for non-browser clients.
fix Ensure that clients making cross-origin requests always include the `Origin` header. For testing purposes, manually add an `Origin` header to simulate browser behavior.
gotcha When using reverse proxies (e.g., Varnish, Nginx, CDNs) in front of your Restify application, incorrect caching configurations can lead to CORS headers being served to the wrong requests. This happens if the proxy does not vary its cache based on the `Origin` request header.
fix Configure your reverse proxy to include `Vary: Origin` in its caching policy. This ensures that different CORS responses (based on `Origin`) are cached separately, preventing unexpected behavior or security issues.
npm install restify-cors-middleware
yarn add restify-cors-middleware
pnpm add restify-cors-middleware

This code sets up a basic Restify server with CORS protection, configuring allowed origins, headers, and demonstrating how to apply the preflight and actual CORS middleware.

const restify = require('restify');
const corsMiddleware = require('restify-cors-middleware');

const server = restify.createServer({
  name: 'my-restify-app'
});

const cors = corsMiddleware({
  preflightMaxAge: 5, // Optional: cache preflight responses for 5 seconds
  origins: [
    'http://localhost:3000', // Example allowed client origin
    'http://myfrontend.com',
    /^https?:\/\/staging\.myfrontend\.com(:[\d]+)?$/ // Regex for staging environment
  ],
  allowHeaders: ['API-Token', 'X-Requested-With'], // Headers client is allowed to send
  exposeHeaders: ['API-Token-Expiry', 'X-Custom-Header'] // Headers client is allowed to read
});

server.pre(cors.preflight); // Handle preflight OPTIONS requests before routing
server.use(cors.actual);    // Handle actual CORS requests and apply headers

server.get('/hello', (req, res, next) => {
  res.send({ message: 'Hello from Restify!' });
  return next();
});

server.listen(8080, () => {
  console.log('%s listening at %s', server.name, server.url);
});