Skip to content

Instantly share code, notes, and snippets.

@danielr18
Created December 8, 2018 04:06
Show Gist options
  • Select an option

  • Save danielr18/f57cd4b3a55cb4117cb7e31d9bd92fc5 to your computer and use it in GitHub Desktop.

Select an option

Save danielr18/f57cd4b3a55cb4117cb7e31d9bd92fc5 to your computer and use it in GitHub Desktop.
Absolute URL from req
import url from 'url'
const defaultValidHostRegex = /www\.example\.com/
export function getProtocol(req) {
let proto = req.connection.encrypted ? 'https' : 'http'
// only do this if you trust the proxy
proto = req.headers['x-forwarded-proto'] || proto
return proto.split(/\s*,\s*/)[0]
}
export function getAbsoluteUrl(req, { fallbackHost = 'www.example.com', validHostRegex = defaultValidHostRegex } = {}) {
let host = req.headers.host || ''
if (!validHostRegex.test(host)) {
host = fallbackHost
}
return url.format({
protocol: getProtocol(req),
host,
pathname: req.url
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment