How to get the full URL in Express and Node.js?

Sometimes, we want to get the full URL in Express and Node.js.

In this article, we’ll look at how to get the full URL in Express and Node.js.

to get the full URL in Express and Node.js

To get the full URL in Express and Node.js, we can use the url package.

To install it, we run

npm i url

Then we can use it by writing

const url = require('url');

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

to define the fullUrl function that takes the Express request req object.

And then we call url.format with an object that has the protocol, host, and pathnameset from the URL components inreq`.

protocol has the protocol like http or ftp.

host has the first segment of the URL after the protocol.

And pathname has the rest of the URL.

Conclusion

To get the full URL in Express and Node.js, we can use the url package.