64

How do I find the a referring sites URL in node?

I'm using express, would I find this in the headers on connect or something?

Thanks!

3 Answers 3

138

In express 4.x:

req.get('Referrer')

This will also check both spellings of referrer so you do not have to do:

 req.headers.referrer || req.headers.referer

Here is the documentation

1
  • HTTP specs's header name is Referer and I find req.get('Referrer') and req.get('Referer') get the same result
    – CDT
    Commented Jan 20, 2022 at 2:16
77

If you mean how do you get it when running an express server, then it's done using the header method on your request:

req.headers.referer;
// => "http://google.com"
3
  • 2
    It should be req.headers['referer']. Commented May 2, 2014 at 10:37
  • 13
    Another option: req.headers.referer Commented May 7, 2014 at 22:13
  • 5
    None of this works for me, I get undefined. This is in express router.
    – geoidesic
    Commented Aug 26, 2022 at 22:58
3

Express 5.0-alpha2 with new JS features.

const referrer = req.get('Referer') ?? req.get('Referrer') ?? null;

I am checking for both spelling as weirdly they can happen sometimes, but it should be super rare.

weirdly just access headers object didn't work for me. It's possible it's only issue with my alpha, but leaving it here for others.

For people having undefined / null

First of all: Referer is not always there. Actually, it's very often not there so make sure you have a fallback. There's a lot of reasons. It can be because someone visited link directly, but it can be also due to privacy settings, browser extensions etc.

Referer can also be also easily spoofed, so using it as a security measure is not really great.

For those cases where it's not empty it can be pretty useful for getting more info about users. Just remember to keep fallback.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.