Get the absolute URL of your site from an Express request, including protocol, hostname and port.
While relative URLs are great, there are cases when you just need to know your site's full URL. These cases might include:
- Rendering the HTML
rel="canonical"
meta tag - Including links to your site in email or push notifications
- Showing the right URL when users share your content on social media.
Turns out this is surprisingly tricky to do right with Express, so this package aims to make it easier:
import { getAbsoluteUrl } from 'express-absolute-url';
> getAbsoluteUrl(req).toString();
https://www.mysite.com/hello/?q=world
Note that a WHATWG URL
object is returned which can be further manipulated or just converted to a
string.
By default, this package will try to determine the port automatically from the incoming Host header (or X-Forwarded-Host header, if you trust that).
If the port could not be determined automatically, then the standard port for
the respective protocol will be used. However, you can still specify the port
manually using the port
option as follows:
import { getAbsoluteUrl } from 'express-absolute-url';
> getAbsoluteUrl(req, { port: 8443 }).toString();
https://www.mysite.com:8443/hello/?q=world
$ npm install express-absolute-url
To run the test suite, first install the dependencies, then run npm test
:
$ npm install
$ npm test
MIT