Parse a URL with memoization for high-performance HTTP request processing
npx @tessl/cli install tessl/npm-parseurl@1.3.0parseurl provides high-performance URL parsing functionality with built-in memoization capabilities for HTTP request objects. It offers optimized parsing that significantly outperforms Node.js native URL parsing, particularly for relative URLs and repeated parsing scenarios.
npm install parseurlconst parseurl = require('parseurl');Note: parseurl is a CommonJS module and does not provide native ES module support.
parseurl implements a high-performance URL parsing system with three key components:
req._parsedUrl and req._parsedOriginalUrl) with automatic cache invalidationurl.parse() for complex URLs and robust error handlingconst parseurl = require('parseurl');
const http = require('http');
http.createServer((req, res) => {
// Parse the request URL with memoization
const parsed = parseurl(req);
console.log('Path:', parsed.pathname);
console.log('Query:', parsed.query);
// Parse the original URL (useful with middleware that modifies req.url)
const originalParsed = parseurl.original(req);
console.log('Original path:', originalParsed.pathname);
res.end('Hello World');
}).listen(3000);Parses the req.url with intelligent caching to avoid redundant parsing operations.
/**
* Parse the req url with memoization
* @param {http.IncomingMessage} req - HTTP request object (Node.js IncomingMessage with url property)
* @returns {ParsedURL|undefined} Parsed URL object or undefined if req.url is undefined
*/
function parseurl(req);Performance Features:
req._parsedUrl to avoid redundant parsingReturn Value:
The function returns a URL object with the same structure as Node.js url.parse():
interface ParsedURL {
/** Full URL string */
href: string;
/** Path portion of URL (pathname + search) */
path: string;
/** Path portion without query string */
pathname: string;
/** Query string including '?' prefix (or null) */
search: string | null;
/** Query string without '?' prefix (or null) */
query: string | null;
/** Host portion including port (or null for relative URLs) */
host: string | null;
/** Host portion without port (or null for relative URLs) */
hostname: string | null;
/** Port portion (or null) */
port: string | null;
}Usage Examples:
const parseurl = require('parseurl');
// In an HTTP server
http.createServer((req, res) => {
const url = parseurl(req);
if (url.pathname === '/api/users') {
// Handle users API
console.log('Full path with query:', url.path); // '/api/users?limit=10&offset=0'
if (url.query) {
// Parse query parameters: url.query contains 'limit=10&offset=0'
const params = new URLSearchParams(url.query);
const limit = params.get('limit');
const offset = params.get('offset');
}
}
// Subsequent calls with same req.url are cached
const cachedUrl = parseurl(req); // Returns cached result
});Parses the req.originalUrl with fallback to req.url and memoization.
/**
* Parse the req original url with fallback and memoization
* @param {http.IncomingMessage} req - HTTP request object (Node.js IncomingMessage with url and optionally originalUrl properties)
* @returns {ParsedURL|undefined} Parsed URL object or undefined if both originalUrl and url are unavailable
*/
function original(req);Fallback Logic:
req.originalUrl is a string: parses req.originalUrlreq.originalUrl is not a string: falls back to parseurl(req)undefinedCaching: Uses req._parsedOriginalUrl property for memoization, separate from the main parseurl() cache.
Usage Examples:
const parseurl = require('parseurl');
const express = require('express');
const app = express();
// Middleware that modifies req.url
app.use('/api', (req, res, next) => {
console.log('Current URL:', parseurl(req).pathname); // '/users' (modified)
console.log('Original URL:', parseurl.original(req).pathname); // '/api/users' (original)
next();
});
app.get('/users', (req, res) => {
res.json({ users: [] });
});parseurl handles errors gracefully:
undefined instead of throwing errorsurl.parse() which may throw for malformed URLsreq.originalUrl is a string before attempting to parseconst parseurl = require('parseurl');
// Safe handling of missing URLs
const parsed = parseurl({ /* no url property */ });
console.log(parsed); // undefined
// Safe handling of non-string originalUrl
const original = parseurl.original({
url: '/path',
originalUrl: 123 // not a string
});
// Falls back to parsing req.url
console.log(original.pathname); // '/path'parseurl provides significant performance improvements over native Node.js URL parsing:
url.parse() for simple pathsBenchmark Results (operations per second):
/foo/bar): ~24M ops/sec vs ~7.5M ops/sec (native)/foo/bar?user=tj): ~4.1M ops/sec vs ~2.6M ops/sec (native)url module only