Skip to content

Get the absolute URL of your site from an Express request

Notifications You must be signed in to change notification settings

mkai/express-absolute-url

Repository files navigation

express-absolute-url

Get the absolute URL of your site from an Express request, including protocol, hostname and port.

NPM Version Build Coverage

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.

Determining the port

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

Installation

$ npm install express-absolute-url

Tests

To run the test suite, first install the dependencies, then run npm test:

$ npm install
$ npm test

License

MIT

About

Get the absolute URL of your site from an Express request

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •