Fluent API to build more readable, stringable and expressive URLs.
Native object extension URL
in TypeScript with chainable methods to handle paths, queries, authentication and fragments easily.
npm install @alexfalconflores/better-url
✨ Features
- Based on native object URL
- Seamless API with method chaining
- Authentication support (auth)
- Dynamic paths with normalization
- Query parameters (query, setQuery, tryQuery, etc.)
- Fragments (#anchor)
- Generic typing for your query parameters
import BetterURL from "better-url";
type Params = {
search: string;
page?: number;
sort?: "asc" | "desc";
};
const url = new BetterURL<Params>("https://example.com");
url.auth("admin", "1234");
// https://admin:1234@example.com
url.portNumber(8080).path("api/v1/users");
// https://admin:1234@example.com:8080/api/v1/users
url.query("search", "john").query("sort", "asc");
// https://.../api/v1/users?search=john&sort=asc
const optionalPage = undefined;
url.tryQuery("page", optionalPage); // No se añade nada
url.setQuery("search", "doe").trySetQuery("page", 2);
// ?search=doe&page=2
url.removeQuery("sort");
url.clearQuery();
// ? (queda vacío)
url.fragment("top");
// #top
console.log(url.toString());
// https://admin:1234@example.com:8080/api/v1/users?search=doe&page=2#top
type QueryParams = {
search: string;
page: number;
};
url.query("search", "hello"); // ✅
url.query("unknown", "value"); // ❌ Error: 'unknown' no está en Params
Method | Description |
---|---|
.auth(user, pass) |
Add credentials to the URL |
.portNumber(port) |
Defines the port |
.path(path) |
Add routes (normalize / ) |
.query(key, value) |
Add a query param (use TQueryParams typing) |
.tryQuery(...) |
Add a query only if the value is not null/undefined |
.setQuery(...) |
Sets or replaces a query |
.trySetQuery(...) |
Same as .setQuery but conditional |
.removeQuery(key) |
Removes a query parameter |
.clearQuery() |
Deletes all parameters |
.fragment(str) |
Add or replace a #fragment
|
Alex Stefano Falcon Flores
- 🐙 GitHub: alexstefano
- 💼 LinkedIn: alexsfalconflores
This project is licensed under the MIT license. See the LICENSE file for more details.
Give the repo a star to support the project! And if you use it in your projects, I'd love to see it! 🎉