How to accept only defined URLs in a NodeJS express API

Viewed 2402

F.E.: My NodeJS script runs on a server with and can handle stuff like:

app.get('/users', function(req, res) {
    res.json([{ name: "Brian" }]);
});

For an API-scenario, I would like to have that only specific websites can place an GET/POST or whatever to the NodeJS API server, before any authentication happens. Is that possible?

2 Answers

A few hints for you

  1. You could create your own middleware to do anything you want:

    Let say I have a middleware:

    const checkdomain = (req, res, next) => {
        //Check domain here
        // ...
        next();
    }
    

    Then you could add this to your router:

    app.get('/users', checkdomain,  function(req, res){});
    
  2. A simple way to whitelist 1 domain (i.e. accept only request from that domain, you could use Access-Control-Allow-Origin header, but it's not a recommend way, as you will depend on request header. I understand from your question, that you already recognised that you need to build your own authentication check, so this domain check is just a additional helper, you should not totally rely on this.

In your checkdomain, you could add:

res.header("Access-Control-Allow-Origin", "https://example.com");

Another way to check:

if( req.headers.host === "https://example.com") { //do stuff }

I think you could achieve this using Cross-Origin Resource Sharing. Although this will only work for browsers, people would still be able to get this data by using CURL or other similar tools.

var cors = require('cors')

and

app.use(cors({
  origin: 'http://example.com'
}))

or

app.use(cors({
  origin: ['http://example1.com', 'http://example2.com']
}))

If you want to read more about it you can check here: https://expressjs.com/en/resources/middleware/cors.html

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Related