Last active
August 15, 2021 05:14
-
-
Save TaylorAckley/461a600705c459df326ffd519366810f to your computer and use it in GitHub Desktop.
Allowed Origins Middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const app = new Express(); | |
const cache = require('origin-cache'); | |
require('api-keys.script'); | |
const allowedOrigins = cache.get(); | |
// see full example: https://github.com/TaylorAckley/cors-app/blob/main/api/index.js | |
/** Use CORS. If RESTRICT_ORIGINS is enabled, only certain domains can call the API. **/ | |
const corsAsync = function (req, callback) { | |
let corsOptions = { origin: false }; | |
const origin = req.header('Origin') | |
const originExists = allowedOrigins.has(origin); | |
if (originExists && req.query.apiKey === allowedOrigins.get(origin)) { | |
corsOptions = { origin: true }; | |
} | |
callback(null, corsOptions); | |
} | |
app.use(cors(corsAsync)); // Activate this middleware for all routes. If you only need some routes protected, look at the Express Router docs. | |
app.options('*', cors(corsAsync)); // Opt in to Browser pre-flight checks. This is important. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@TaylorAckley I have read your blog and it helped me in setting up dynamic cors. I have some concerns. Can you please let me know how to ready custom headers in cors middleware. Like you read origin which is allowed by default. So I want to pass clientId as a header in the request and based on clientId I want to fetch the origins from DB and process further. But I am not able to read the custom header that I have passed in the header.