Restify CORS Middleware
raw JSON →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.
Common errors
error CORS headers are missing or incorrect for my client requests. ↓
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. ↓
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. ↓
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. Warnings
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. ↓
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. ↓
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. ↓
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. ↓
Install
npm install restify-cors-middleware yarn add restify-cors-middleware pnpm add restify-cors-middleware Imports
- corsMiddleware wrong
import corsMiddleware from 'restify-cors-middleware'correctconst corsMiddleware = require('restify-cors-middleware')
Quickstart
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);
});