389

I'd like to get the "Host" header of a request made using Node JS's connect library bundle. My code looks like:

var app = connect()
  .use(connect.logger('dev'))
  .use(connect.static('public'))
  .use(function(req, res){

    var host = req.???

  })
 .listen(3000);

The documentation for connect is here but I don't see anything detailing the API of the req object in the above code. http://www.senchalabs.org/connect/

Edit: Note a successful answer must point to the documentation (I need this to verify which version provided the API I'm looking for).

Alex Spurling
  • 54,094
  • 23
  • 70
  • 76

6 Answers6

450

If you use Express 4.x, you can use the req.get(headerName) method as described in Express 4.x API Reference

gilly3
  • 87,962
  • 25
  • 144
  • 176
Sami
  • 5,819
  • 1
  • 23
  • 30
  • 230
    Also aliased with the better-named `req.header(headerName)`. – ZachB Dec 19 '16 at 22:58
  • 12
    No need to bring in Express for basic functionality like this one. Instead use natively in NodeJS as mentioned below. https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/ – CodeFinity Jun 11 '18 at 02:59
  • ...was it to difficult for them to call it getHeader()? javascript never fails to amaze. btw. .get()/header() are case insensitive but .headers[] is case-sensitive – Welcor Jun 13 '23 at 15:31
329

To see a list of HTTP request headers, you can use :

console.log(JSON.stringify(req.headers));

to return a list in JSON format.

{
"host":"localhost:8081",
"connection":"keep-alive",
"cache-control":"max-age=0",
"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"upgrade-insecure-requests":"1",
"user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36",
"accept-encoding":"gzip, deflate, sdch",
"accept-language":"en-US,en;q=0.8,et;q=0.6"
}
Luke
  • 565
  • 5
  • 19
user2775422
  • 3,391
  • 1
  • 11
  • 3
  • 5
    I found this more helpful than the accepted answer above. The JSON.stringify makes all the difference. – Patrick Sep 08 '15 at 20:39
  • 1
    Totally- on a related note, you can also do: `require('util').inspect(req.headers, {depth: null}` if you want the equivalent of what you'd get in the Node REPL. Either way you end up w/ a string. – mikermcneil Dec 13 '15 at 02:59
  • 8
    Why isn't `req.headers` included in the official Express documentation? https://expressjs.com/en/api.html#req – user1063287 Aug 13 '18 at 06:09
  • does not work for a Header object (Symbol object) of a response - res.headers. – Codebeat Aug 28 '18 at 15:04
  • 6
    Stating the obvious here : `headerValue = req.headers['headerName']; ` – asokan Aug 21 '19 at 15:56
  • I don't know why Express doesn't have this documented, and intentionally hiding this information. I need ALL headers but not particular headers. – ShiraishiMai May 14 '20 at 08:11
  • 8
    They just document those properties that are not derived. There is a note in the Express documentation mentioned above: _"The req object is an enhanced version of Node’s own request object and supports all [built-in fields and methods](https://nodejs.org/api/http.html#http_class_http_incomingmessage)."_ that contains a link pointing to the Node documentation of the underlying object. – Serge N May 15 '20 at 19:30
164

Check output of console.log(req) or console.log(req.headers);

Anatoliy
  • 29,485
  • 5
  • 46
  • 45
  • 14
    How did you find out about req.headers? In which version is this field available? – Alex Spurling Oct 30 '12 at 21:31
  • 14
    @AlexSpurling http://nodejs.org/api/http.html#http_request_headers. Connect just extends types from Node's [HTTP module](http://nodejs.org/api/http.html) -- [`http.ServerRequest`](http://nodejs.org/api/http.html#http_class_http_serverrequest) and [`http.ServerResponse`](http://nodejs.org/api/http.html#http_class_http_serverresponse). Properties or events found in Node's documentation should also be available with Connect (and, by further extension, Express). – Jonathan Lonowski Oct 30 '12 at 21:35
  • 1
    That makes more sense. Again, it would be good to know where to find that information (that the type of req is actually http.ServerRequest). The documentation doesn't appear to make this clear. – Alex Spurling Oct 30 '12 at 21:58
  • 1
    Type of req is http.IncomingMessage – Anatoliy Oct 30 '12 at 23:07
  • This gist emulates http request and it may be useful for you: https://gist.github.com/3879071 – Anatoliy Oct 30 '12 at 23:09
  • @AlexSpurling "An [IncomingMessage](https://nodejs.org/api/http.html#http_http_incomingmessage) object is created by http.Server or http.ClientRequest and passed as the first argument to the 'request' and 'response' event respectively. It may be used to access response status, headers and data." You can find an example here https://nodejs.org/api/http.html#http_message_headers. – gihanchanuka Sep 03 '15 at 08:21
  • I'm trying to understand code that contains `app.use((req, res, next) => { if (req.headers && req.headers.authorization && req.headers.authorization.split(' ')[0] === 'JWT')`.....and `headers` does not seem to be mentioned anywhere in the Request object docs: https://expressjs.com/en/api.html#req . Is there a comprehensive list of these types of undocumented properties anywhere? – user1063287 May 15 '18 at 12:49
  • Use `JSON.stringify()` as mentioned below. – CodeFinity Jun 11 '18 at 03:00
  • @user1063287 The express documentation states that the express Request object is "an enhanced version of Node’s own request object and supports all [built-in fields and methods](https://nodejs.org/api/http.html#http_class_http_incomingmessage)". In other words, the express documentation doesn't mention the built-in properties like `req.headers`. – Sidney Jul 19 '18 at 19:12
87
var host = req.headers['host']; 

The headers are stored in a JavaScript object, with the header strings as object keys.

Likewise, the user-agent header could be obtained with

var userAgent = req.headers['user-agent']; 
Brad
  • 159,648
  • 54
  • 349
  • 530
Bonkles
  • 981
  • 6
  • 4
  • 7
    NOTE: the named index value is FreakING!! case sensitative – Steve Mar 16 '17 at 03:04
  • 15
    As per @Steve comment about it being case sensitive all headers are lower-cased. So if you are setting the header "Origin" (capital 'O') then the only element in the request headers collection will be "origin" with a lowercase 'o'. – rob Jun 09 '17 at 09:43
  • @Steve - FWIW, headers are not supposed to be case sensitive. The Http spec specifically says they are treated as case insensitive. For Http2 they must be lowercased for transmission, but that doesnt make them case sensitive on either end, so what we got is an http header implementation thats bugged =/. – StingyJack Aug 21 '21 at 03:35
  • that is because nodejs stores them like a dict. and those dict keys are case sensitive. Doesnt mean that i support that behavior, but that is the reason for it. – Welcor Jun 13 '23 at 15:33
6
logger.info({headers:req.headers})

Output;

 "headers":{"authorization":"Basic bmluYWQ6bmluYWQ=","content-
type":"application/json","user-
agent":"PostmanRuntime/7.26.8","accept":"*/*","postman-token":"36e0d84a-
55be-4661-bb1e-1f04d9499574","host":"localhost:9012","accept-
encoding":"gzip, deflate, br","connection":"keep-alive","content-
length":"198"}
suraj gholap
  • 347
  • 4
  • 3
1

In express, we can use request.headers['header-name'], For example if you have set up a Bearer token in authorization header and want to retrieve the token, then you should write req.headers['authorization'], and you will get the string containing 'Bearer tokenString'.