A plugin to provide access to a URL object
MIT License
A plugin for fastify for accessing an incoming request's URL data.
fastify-url
is inspired by fastify-url-data
and is just a thin wrapper around Node's URL object.
const fastify = require('fastify')();
fastify.register(require('fastify-url').default);
fastify.get('/*', (req, reply) => {
const url = req.url();
req.log.info(url.host); // 'sub.example.com:8080'
req.log.info(url.hostname); // 'sub.example.com'
req.log.info(url.href); // 'http://user:[email protected]:8080/p/a/t/h?query=string'
req.log.info(url.origin); // 'http://sub.example.com:8080'
req.log.info(url.password); // 'pass'
req.log.info(url.pathname); // '/p/a/t/h'
req.log.info(url.port); // '8080'
req.log.info(url.protocol); // 'http:'
req.log.info(url.search); // '?query=string'
req.log.info(url.username); // 'user'
// if you just need single data:
req.log.info(req.url('pathname')); // '/p/a/t/h'
reply.send();
});
// GET: 'http://user:[email protected]:8080/p/a/t/h?query=string'
Type: string
Default: http
This property allows you to change the protocol the incoming request's URL object will absorb. This is used because it's difficult to find the protocol the request was received from within the request handler.
fastify-url
vs fastify-url-data
The difference between these two plugins is fastify-url
uses the native NodeJS URL class and fastify-url-data
uses uri-js
. These implementations provide some of the same features but have different data members. Depending on your requirements you may need one or the other, but using both is redundant.