Skip to content

Instantly share code, notes, and snippets.

@maxholman
Last active September 7, 2022 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxholman/aef4b06f56cd55acfba7770298fb323a to your computer and use it in GitHub Desktop.
Save maxholman/aef4b06f56cd55acfba7770298fb323a to your computer and use it in GitHub Desktop.
Simple CORS for Express
import type { IncomingHttpHeaders } from 'node:http';
import type { RequestHandler } from 'express';
interface CorsOptions {
allowedOrigin:
| string
| ((
origin: string | undefined,
headers: IncomingHttpHeaders,
) => string | false | null | undefined);
maxAge?: number;
allowedMethods?: string[];
allowedHeaders?: string[];
exposedHeaders?: string[];
credentials?: boolean;
}
export const corsBuilder = (options?: CorsOptions): RequestHandler => (req, res, next) => {
// no origin header? just bypass everything
if (!req.headers.origin) {
return next();
}
const requestOrigin = req.headers.origin;
res.vary('origin');
if (options?.credentials) {
res.set(
'Access-Control-Allow-Credentials',
options.credentials.toString(),
);
}
if (options?.exposedHeaders) {
res.set(
'Access-Control-Expose-Headers',
options.exposedHeaders.join(','),
);
}
if (options?.allowedOrigin) {
try {
const allowOrigin =
options.allowedOrigin instanceof Function
? options.allowedOrigin(requestOrigin, req.headers)
: options.allowedOrigin;
if (allowOrigin) {
res.set('Access-Control-Allow-Origin', allowOrigin);
}
} catch (err) {
return next(err);
}
} else {
res.set('Access-Control-Allow-Origin', '*');
}
if (req.method === 'OPTIONS') {
if (options?.allowedHeaders) {
if (options.allowedHeaders.length > 0) {
res.set(
'Access-Control-Allow-Headers',
options.allowedHeaders.join(','),
);
}
} else if (req.headers['access-control-request-headers']) {
res.vary('access-control-request-headers');
res.set(
'Access-Control-Allow-Headers',
req.headers['access-control-request-headers'].slice(0, 512),
);
}
if (options?.allowedMethods) {
if (options.allowedMethods.length > 0) {
res.set(
'Access-Control-Allow-Methods',
options.allowedMethods.join(','),
);
}
} else if (req.headers['access-control-request-methods']) {
res.vary('access-control-request-methods');
res.set(
'Access-Control-Allow-Methods',
req.headers['access-control-request-methods'].slice(0, 512),
);
}
if (options?.maxAge) {
res.set('Access-Control-Max-Age', (5 * 60).toString());
}
res.status(204).send();
} else {
next();
}
};

Copyright 2022 Block65 Pte Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment