referrer-typed v1.0.4
referrer-typed
Express middleware to redirect on certain Referer header fields.
Useful for example to avoid direct download linking from third party sites.
Comes with typings (for TypeScript).
Installation
npm
npm install referrer-typed
yarn
yarn add referrer-typed
Examples
Notice that the module is written in TypeScript and transpiled down to ES5.
JavaScript
Here we are going to shield our download route with a referrer protection:
var Referrer = require('referrer-typed').Referrer;
var config = {
allowNoReferrer: true,
redirectTo: '/',
regexExclude: /http:\/\/test.org\/.*/
};
var referrer = new Referrer(config);
app.get('/download/*', referrer.check.bind(referrer));
The configuration is set to allow missing Referer
headers fields (optional, default is false
),
something you probably don't want to permit as a matter of fact.
It will redirect to the root of the website defined by redirectTo
. Referrer fields
matching the regular expression in regexExclude
will cause a redirect, everything
will be passed to the next handler.
Probably more common are inclusive restrictions:
var Referrer = require('referrer-typed').Referrer;
var config = {
redirectTo: '/index.html',
regexInclude: [ /yes.com/, /ok/ ],
onRedirect: function(req, referrer) {
console.log('redirected', req.ip, 'because of', referrer);
}
};
var referrer = new Referrer(config);
app.get('/download/*', referrer.check.bind(referrer));
Here any referrer carrying yes.com
or ok
will be let through. Everything else
gets directed to /index.html
. We also add a callback in onRedirect
to log the
request and the extracted referrer in case we do redirect.
This covers all of the configuration fields.
TypeScript
If you use TypeScript please check out the IReferrerConfig
interface for further information.