CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-ufo

URL utils for humans with comprehensive parsing, manipulation, encoding, and normalization functions.

Pending
Overview
Eval results
Files

query.mddocs/

Query String Handling

Comprehensive query string parsing and manipulation with support for arrays, nested objects, and complex data types. Includes built-in protection against prototype pollution and flexible serialization options for different data structures.

Capabilities

Parse Query String

Converts query strings into structured objects with automatic handling of duplicate keys and arrays.

/**
 * Parses and decodes a query string into an object
 * @param parametersString - Query string with or without leading '?'
 * @returns Parsed query object with string/array values
 */
function parseQuery<T extends ParsedQuery = ParsedQuery>(parametersString?: string): T;

type ParsedQuery = Record<string, string | string[]>;

Usage Examples:

import { parseQuery } from "ufo";

// Basic query parsing
const basic = parseQuery("name=John&age=30&active=true");
// { name: 'John', age: '30', active: 'true' }

// With leading question mark
const withQ = parseQuery("?search=javascript&category=web");
// { search: 'javascript', category: 'web' }

// Array handling (duplicate keys)
const arrays = parseQuery("tags=javascript&tags=web&tags=api");
// { tags: ['javascript', 'web', 'api'] }

// URL-encoded values
const encoded = parseQuery("message=hello%20world&special=%21%40%23");
// { message: 'hello world', special: '!@#' }

// Empty and special cases
const empty = parseQuery("key1=&key2=value&key3");
// { key1: '', key2: 'value', key3: '' }

Stringify Query Object

Converts query objects back into query string format with proper encoding.

/**
 * Stringifies and encodes a query object into a query string
 * @param query - Object with string, number, boolean, array, or object values
 * @returns Encoded query string without leading '?'
 */
function stringifyQuery(query: QueryObject): string;

type QueryObject = Record<string, QueryValue | QueryValue[]>;
type QueryValue = string | number | undefined | null | boolean | Array<QueryValue> | Record<string, any>;

Usage Examples:

import { stringifyQuery } from "ufo";

// Basic object to query string
const basic = stringifyQuery({ name: "John", age: 30, active: true });
// "name=John&age=30&active=true"

// Array values
const arrays = stringifyQuery({ tags: ["javascript", "web", "api"] });
// "tags=javascript&tags=web&tags=api"

// Complex objects (JSON stringified)
const complex = stringifyQuery({
  user: { name: "John", email: "john@example.com" },
  preferences: ["dark-mode", "notifications"]
});
// "user=%7B%22name%22%3A%22John%22%2C%22email%22%3A%22john%40example.com%22%7D&preferences=dark-mode&preferences=notifications"

// Filtering undefined values
const filtered = stringifyQuery({ a: "value", b: undefined, c: null });
// "a=value&c=null" (undefined values are filtered out)

Encode Query Item

Encodes individual query key-value pairs with proper array handling.

/**
 * Encodes a pair of key and value into a URL query string format
 * @param key - Query parameter key
 * @param value - Value(s) to encode, can be single value or array
 * @returns Encoded query string segment
 */
function encodeQueryItem(key: string, value: QueryValue | QueryValue[]): string;

Usage Examples:

import { encodeQueryItem } from "ufo";

// Single value
const single = encodeQueryItem("name", "John Doe");
// "name=John+Doe"

// Array values
const array = encodeQueryItem("colors", ["red", "green", "blue"]);
// "colors=red&colors=green&colors=blue"

// Special value types
const number = encodeQueryItem("count", 42);
// "count=42"

const boolean = encodeQueryItem("active", true);
// "active=true"

// Empty or null values
const empty = encodeQueryItem("empty", "");
// "empty="

const nullValue = encodeQueryItem("null", null);
// "null"

// Object values (JSON stringified)
const object = encodeQueryItem("data", { key: "value" });
// "data=%7B%22key%22%3A%22value%22%7D"

Security Features

Prototype Pollution Protection

The parseQuery function includes built-in protection against prototype pollution attacks:

// These dangerous keys are automatically ignored
parseQuery("__proto__=malicious&constructor=bad&normal=good");
// { normal: 'good' } - dangerous keys filtered out

Safe Encoding

All encoding functions handle edge cases gracefully:

  • Invalid input types are converted to strings
  • Malformed encoding doesn't throw errors
  • Special characters are properly escaped
  • Unicode characters are handled correctly

Advanced Usage Patterns

Building Search URLs

import { withQuery } from "ufo"; // From utilities module

const searchUrl = withQuery("/search", {
  q: "javascript tutorials",
  category: "programming",
  tags: ["beginner", "web"],
  limit: 20
});
// "/search?q=javascript+tutorials&category=programming&tags=beginner&tags=web&limit=20"

Processing Form Data

import { parseQuery, stringifyQuery } from "ufo";

// Parse form data from URL
const formData = parseQuery(window.location.search.slice(1));

// Modify and rebuild
const updatedData = {
  ...formData,
  page: parseInt(formData.page as string) + 1,
  timestamp: Date.now()
};

const newQueryString = stringifyQuery(updatedData);

API Parameter Handling

import { stringifyQuery } from "ufo";
import { getQuery } from "ufo"; // getQuery is in utilities module

// Extract API parameters
const apiParams = getQuery(request.url);

// Add server-side parameters
const enrichedParams = {
  ...apiParams,
  apiKey: process.env.API_KEY,
  version: "v2"
};

// Build API request URL
const apiUrl = `https://api.service.com/data?${stringifyQuery(enrichedParams)}`;

Install with Tessl CLI

npx tessl i tessl/npm-ufo

docs

encoding.md

index.md

parsing.md

query.md

url-class.md

utilities.md

tile.json