javascriptnode.jsreactjsexpresscors

How can I disable CORS for a single route in Express without rewriting all of my routes?


TLDR: In the example, I just want to make it so that /users/delete cannot be called by anything outside of my React app.

I have a bunch of routes for the backend API of my app that uses Express:

ie. server.js

app.get('/invoices/read', async (req, res) => {
    // gather data from db
    res.json({...data})
})

I have cors enabled globally like so:

server.js

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );
  next();
});

So, my question is, how would I disable CORS for a single route such as this

app.post('/users/delete', async (req, res) => {
    // delete user out of database
    res.sendStatus(200)
})

without rewriting all of my routes to something like this:

var cors = require('cors');

app.get('/invoices/read', cors(), async (req, res) => {
    // gather data from db
    res.json({...data})
})

So that a user can't just make a POST request to /users/delete using an arbitrary ID in an attempt to delete a user out of my system?

Do I need to just include the origin in my headers or do I need to disable CORS for that route?


Solution

  • Override the header only on the route you want to "disable" it:

    res.set('Access-Control-Allow-Origin', 'alloweddomain.com')
    

    If you need to allow more than one domain, you can make a list of allowed domains and check if the origin is included there:

    const allowedDomains = ['allowedomain1.com', 'alloweddomain2.com'];
    const origin = req.get('origin');
    
    if (allowedDomains.includes(origin)) {
      res.set('Access-Control-Allow-Origin', origin);
    }