HTTP Request Referer in Meteor Iron Router
-
21-12-2019 - |
Question
I have a server side route in my Meteor app where I can get, for instance, the client's IP:
this.route('foo', {
where: 'server',
path: '/bar',
action: function () {
var ip = context.request.connection.remoteAddress;
}
});
How can I access the referer field? Do I need to use Meteor Headers?
Solution
You can directly access the connect request object, which has the headers:
this.request.headers['referer']
Like this:
Router.map(function () {
this.route('foo', {
where: 'server',
path: '/bar',
action: function () {
console.log("All headers:", this.request.headers);
console.log("Referer:", this.request.headers['referer']);
}
})
});
OTHER TIPS
I just had the same problem and after some more digging I figured out if the source page was secure (HTTPS) the browser will not send the referer.
As well if the source document is on the local computer a referer is not available. That fooled me for a while as I simply created a test.html
on the Desktop for testing...
So the code in my route for blocking direct requests to this route from other websites looks like this now:
action: function () {
var self = this;
var host = self.request.headers.host;
var referer = self.request.headers.referer;
var regex = new RegExp("^http(?:s)?://" + host);
if(typeof self.request.headers.referer !== "undefined" && !regex.test(referer)) {
Meteor.log.error("Access blocked from " + referer);
self.response.statusCode = 403;
self.response.end(Handlebars.templates['403']());
return;
}
}
If the referer is set, it has to match the current hostname.
you can do document.referrer to get that information
alternatively you can use History API: history.go(-1);