Home > Mobile >  How do I block routes from a certain origin with cors and expressjs
How do I block routes from a certain origin with cors and expressjs

Time:03-02

Right now I have enabled cors so it only allows one origin that can make a request to ANY ROUTE, but I want to make it so it also blocks some routes for that one origin. If their is any way, please answer this question! Thank you.

So far my code is

app.use(cors({
  origin: process.env.HOST,
}));

CodePudding user response:

I think you can try something like this

const blacklisted = ['http://example1.com', 'http://example2.com']
const corsOptions = {
  origin: function (origin, callback) {
    if (blacklisted.indexOf(origin) !== -1) {
        callback(new Error('Not allowed by CORS'))
    } else {
        callback(null, true)
    }
  },
}

Then you can use it like this,

app.get('/route', cors(corsOptions), (req, res, next) => {
  //...
})
  • Related