Brad
Brad

Reputation: 331

Can I only accept traffic from certain requesting domains with Expressjs?

I would like to be able to only let requests from a very specific domain get successfully served by a node app I have on heroku.

The code I tried is

app.use((req, res, next) => {
  if (req.hostname === "example.com") {
    next();
    }
});

Turns out req.hostname seems to be the name of my heroku appserver... I've looked over the express docs for the req object but don't see anything else promising.

(I see IP is a possibility but the IP situation for where the traffic is coming from changes from time to time and I'm not in the loop on that.)

I feel like the domain of the request has to be somewhere... But maybe what I want isn't possible.

Upvotes: 6

Views: 7668

Answers (1)

jfriend00
jfriend00

Reputation: 707328

accept a request from example.com is where you have things goofed up. That request isn't coming from example.com. That request is coming from some individual computer who is displaying a web page that they got from example.com. Anyone on the internet can load and run that same web page.

Authentication is typically how you limit who can access what. You require the user to enter some form of credential. You can limit access by client IP (with various limitations), but you've already indicated you don't think that will work.

The usual schemes for limiting who can access your server's functionality are:

  1. Use some sort of authentication scheme (require user to enter a credential to "log in"). This can be your own auth scheme or can piggy back on some other existing auth scheme.
  2. Whitelist access to your server from only a specific client IP address or range of IP addresses. This is not used very often because it has all sorts of limitations.

FYI, as long as your server does not allow cross origin requests (which it will not by default), then some other web site can't access your server via a browser (the browser will prevent it). But, any script junkie or hacker still can. Only authentication or IP filtering will prevent a hacker from accessing your service.

Upvotes: 14

Related Questions