@alexfalconflores/better-url
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

BetterURL
BetterURL logo

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.


🚀 Installation

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

📦 Examples of use

⚙️ Create a new instance

import BetterURL from "better-url";

type Params = {
  search: string;
  page?: number;
  sort?: "asc" | "desc";
};

const url = new BetterURL<Params>("https://example.com");

🔐 auth

url.auth("admin", "1234");
// https://admin:1234@example.com

🔧 portNumber y path

url.portNumber(8080).path("api/v1/users");
// https://admin:1234@example.com:8080/api/v1/users

🧭 query

url.query("search", "john").query("sort", "asc");
// https://.../api/v1/users?search=john&sort=asc

❔tryQuery

const optionalPage = undefined;

url.tryQuery("page", optionalPage); // No se añade nada

🔁 (setQuery, trySetQuery)

url.setQuery("search", "doe").trySetQuery("page", 2);
// ?search=doe&page=2

❌ (removeQuery, clearQuery)

url.removeQuery("sort");
url.clearQuery();
// ? (queda vacío)

🧩 (fragment)

url.fragment("top");
// #top

🧪 Final result

console.log(url.toString());
// https://admin:1234@example.com:8080/api/v1/users?search=doe&page=2#top

🧠 Strong typing

type QueryParams = {
  search: string;
  page: number;
};

url.query("search", "hello"); // ✅
url.query("unknown", "value"); // ❌ Error: 'unknown' no está en Params

🧰 Available methods

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

👤 Autor

Alex Stefano Falcon Flores

📄 License

This project is licensed under the MIT license. See the LICENSE file for more details.

⭐ Do you like it?

Give the repo a star to support the project! And if you use it in your projects, I'd love to see it! 🎉

Package Sidebar

Install

npm i @alexfalconflores/better-url

Weekly Downloads

9

Version

1.0.1

License

MIT

Unpacked Size

16.3 kB

Total Files

12

Last publish

Collaborators

  • alexfalconflores