HTTP URL Builder
http-url-builder is a lightweight utility designed to simplify the construction of HTTP URLs, primarily for REST API interactions. It provides a fluent API to append path segments, add query parameters, and integrate path variables, streamlining the process of creating complex endpoints. The current stable version is 1.1.0, which notably introduced support for path variables. As a relatively new but actively maintained package, its release cadence is feature-driven, with updates focused on enhancing usability and functionality. Key differentiators include its explicit support for path variables, a clear and chainable API, and native TypeScript typings, which ensure a robust development experience compared to manual string concatenation or less specialized URL manipulation libraries.
Common errors
-
TypeError: URLBuilder is not a constructor
cause Attempting to instantiate `URLBuilder` as a default export or incorrectly using `require` for a named export.fixEnsure you are using `import { URLBuilder } from 'http-url-builder';` if the library exports it as a named export. If using CommonJS, check the library's documentation for the correct `require` syntax, which might involve `const { URLBuilder } = require('http-url-builder');` or `const URLBuilder = require('http-url-builder').URLBuilder;`. -
Error: Path variable '{variableName}' not provided in withPathVariables.cause A placeholder like `/{variableName}` was included in an `addPath` call, but no corresponding key-value pair was supplied to the `withPathVariables` method.fixEnsure that every path variable placeholder defined within `addPath` (e.g., `{userId}`) has an exact matching key in the object passed to `withPathVariables({ userId: 'actualValue' })` before calling `build()`.
Warnings
- breaking Prior to version 1.1.0, explicit support for `path variables` (e.g., `/users/{id}`) was not available. While manual string concatenation might have been used, the `withPathVariables` method was introduced in v1.1.0, requiring adoption of the new API for dynamic path segments.
- gotcha The `URLBuilder` automatically handles URL encoding for query parameters and path segments. However, ensure that any base URLs or manually added path segments do not contain already encoded parts that should not be re-encoded, as this can lead to double encoding issues. For path variables, ensure the variable name in `addPath` (e.g., `{userId}`) exactly matches the key in `withPathVariables({ userId: 'value' })`.
- gotcha When using `addQuery` with multiple values for the same key, the builder typically appends them, potentially creating `?key=value1&key=value2`. Understand the expected behavior for your API. If your API expects comma-separated values (e.g., `?key=value1,value2`), you may need to construct the value string manually before passing it to `addQuery`.
Install
-
npm install http-url-builder -
yarn add http-url-builder -
pnpm add http-url-builder
Imports
- URLBuilder
const URLBuilder = require('http-url-builder');import { URLBuilder } from 'http-url-builder'; - URLBuilderOptions
import type { URLBuilderOptions } from 'http-url-builder'; - buildUrl
import { buildUrl } from 'http-url-builder';
Quickstart
import { URLBuilder } from 'http-url-builder';
interface UserProfile { id: string; name: string; age: number; status: 'active' | 'inactive'; }
const API_BASE = 'https://api.example.com';
// Build a URL for fetching a user profile by ID
const userProfileUrl = new URLBuilder(API_BASE)
.addPath('/users')
.addPath('/{userId}')
.withPathVariables({ userId: '123' })
.addQuery('fields', 'id,name,status')
.addQuery('expand', 'posts')
.build();
console.log(`User Profile URL: ${userProfileUrl}`);
// Expected: https://api.example.com/users/123?fields=id,name,status&expand=posts
// Build a URL for searching users with specific criteria
const searchUsersUrl = new URLBuilder(API_BASE)
.addPath('/search')
.addQuery('query', 'john doe')
.addQuery('limit', 10)
.addQuery('page', 2)
.build();
console.log(`Search Users URL: ${searchUsersUrl}`);
// Expected: https://api.example.com/search?query=john+doe&limit=10&page=2
// Example with optional parameters and encoding
const itemSearchUrl = new URLBuilder('https://store.example.com')
.addPath('/items')
.addQuery('category', 'electronics')
.addQuery('q', 'usb-c adapter & charger') // Spaces and special chars handled
.build();
console.log(`Item Search URL: ${itemSearchUrl}`);
// Expected: https://store.example.com/items?category=electronics&q=usb-c+adapter+%26+charger