How to get the full URL in Express? How to get the full URL in Express? express express

How to get the full URL in Express?


  1. The protocol is available as req.protocol. docs here

    1. Before express 3.0, the protocol you can assume to be http unless you see that req.get('X-Forwarded-Protocol') is set and has the value https, in which case you know that's your protocol
  2. The host comes from req.get('host') as Gopal has indicated

  3. Hopefully you don't need a non-standard port in your URLs, but if you did need to know it you'd have it in your application state because it's whatever you passed to app.listen at server startup time. However, in the case of local development on a non-standard port, Chrome seems to include the port in the host header so req.get('host') returns localhost:3000, for example. So at least for the cases of a production site on a standard port and browsing directly to your express app (without reverse proxy), the host header seems to do the right thing regarding the port in the URL.

  4. The path comes from req.originalUrl (thanks @pgrassant). Note this DOES include the query string. docs here on req.url and req.originalUrl. Depending on what you intend to do with the URL, originalUrl may or may not be the correct value as compared to req.url.

Combine those all together to reconstruct the absolute URL.

  var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;


Instead of concatenating the things together on your own, you could instead use the node.js API for URLs and pass URL.format() the informations from express.

Example:

var url = require('url');function fullUrl(req) {  return url.format({    protocol: req.protocol,    host: req.get('host'),    pathname: req.originalUrl  });}


I found it a bit of a PITA to get the requested url. I can't believe there's not an easier way in express. Should just be req.requested_url

But here's how I set it:

var port = req.app.settings.port || cfg.port;res.locals.requested_url = req.protocol + '://' + req.host  + ( port == 80 || port == 443 ? '' : ':'+port ) + req.path;