npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

ofetch-utils

v0.3.1

Published

Utility functions and hooks for ofetch to simplify URL template parameter binding and route parameter extraction

Readme

ofetch-utils

npm version npm downloads bundle JSDocs License

Utility functions and hooks for ofetch to simplify URL template parameter binding and route parameter extraction.

Features

  • 🔗 URL Template Parameter Binding - Replace {param} and :param placeholders with actual values
  • 🪝 ofetch Hook Integration - Seamless integration with ofetch's request/response lifecycle
  • 🎯 Multiple Parameter Styles - Support for OpenAPI ({param}) and H3/Express (:param) patterns
  • 🛡️ Type Safe - Full TypeScript support with comprehensive type definitions
  • 🔄 Auto-detection - Automatically detect and handle different parameter styles
  • 📦 Zero Dependencies - Lightweight with no external dependencies (except ofetch peer dependency)
  • 🧪 Well Tested - Comprehensive test coverage for all functionality

Installation

# npm
npm install ofetch-utils

# yarn
yarn add ofetch-utils

# pnpm
pnpm add ofetch-utils

Quick Start

Basic URL Template Binding

import { bindUrlTemplateParams } from 'ofetch-utils'

// Replace parameters in URL templates
const url = bindUrlTemplateParams('/users/{userId}/posts/{postId}', {
  userId: '123',
  postId: 'hello-world'
})
// Result: '/users/123/posts/hello-world'

ofetch Hook Integration

import { ofetch } from 'ofetch'
import { bindRequestParamsHook } from 'ofetch-utils'

// Create an ofetch client with automatic parameter binding
const client = ofetch.create({
  onRequest: bindRequestParamsHook()
})

// Use template URLs directly in requests
const user = await client('/users/{userId}', {
  params: { userId: '123' }
})
// Automatically requests: /users/123

API Reference

bindUrlTemplateParams(templateUrl, pathParams, options?)

Replaces URL template parameters with actual values from an object.

Parameters:

  • templateUrl (string) - URL template with parameter placeholders
  • pathParams (Record<string, any>) - Object containing parameter values
  • options.mode? ('auto' | 'openapi' | 'h3') - Parameter detection mode (default: 'auto')

Returns: string - URL with parameters replaced and properly encoded

Examples:

// OpenAPI style parameters
bindUrlTemplateParams('/api/{version}/users/{id}', {
  version: 'v1',
  id: 456
})
// Result: '/api/v1/users/456'

// H3/Express style parameters
bindUrlTemplateParams('/users/:userId/posts/:postId', {
  userId: 'john',
  postId: 'my-post'
})
// Result: '/users/john/posts/my-post'

// Mixed styles (auto-detection)
bindUrlTemplateParams('/api/{version}/users/:id', {
  version: 'v2',
  id: 'jane'
})
// Result: '/api/v2/users/jane'

// URL encoding of special characters
bindUrlTemplateParams('/search/{query}', {
  query: 'hello world & more'
})
// Result: '/search/hello%20world%20%26%20more'

extractRouteParamsFromQuery(url, options?)

Extracts route parameters from a URL and retrieves their values from query string or provided options.

Parameters:

  • url (string) - Complete URL with route pattern and optional query string
  • options.mode? ('auto' | 'openapi' | 'h3') - Parameter detection mode
  • options.params? (Record<string, any>) - Parameter values (highest priority)
  • options.query? (Record<string, any>) - Query values (medium priority)

Returns: Record<string, string | undefined> - Object with parameter names and values

Examples:

// Extract from query string
extractRouteParamsFromQuery('/users/{userId}/posts/{postId}?userId=123&postId=456')
// Result: { userId: '123', postId: '456' }

// Use provided params
extractRouteParamsFromQuery('/users/{userId}', {
  params: { userId: 123 }
})
// Result: { userId: '123' }

// Mixed parameter styles
extractRouteParamsFromQuery('/api/{version}/users/:userId', {
  mode: 'auto',
  query: { version: 'v1', userId: 'john' }
})
// Result: { version: 'v1', userId: 'john' }

bindRequestParamsHook(options?)

Creates an ofetch hook that automatically binds URL template parameters from request options.

Parameters:

  • options.mode? ('auto' | 'openapi' | 'h3') - Parameter detection mode (default: 'auto')

Returns: FetchHook - Hook function for use with ofetch

Examples:

import { ofetch } from 'ofetch'
import { bindRequestParamsHook } from 'ofetch-utils'

// Basic usage
const client = ofetch.create({
  onRequest: bindRequestParamsHook()
})

await client('/users/{userId}/posts/{postId}', {
  params: { userId: '123', postId: 'hello-world' }
})
// Requests: /users/123/posts/hello-world

// With specific mode
const apiClient = ofetch.create({
  onRequest: bindRequestParamsHook({ mode: 'openapi' })
})

// Multiple hooks
const advancedClient = ofetch.create({
  onRequest: [
    bindRequestParamsHook(),
    // other hooks...
  ]
})

// Works with different parameter styles
await client('/users/:userId/posts/{postId}', {
  params: { userId: '123', postId: 'hello' }
})
// In auto mode, both :userId and {postId} are replaced

Parameter Detection Modes

auto (Default)

Automatically detects and processes both OpenAPI ({param}) and H3 (:param) style parameters.

'/api/{version}/users/:id' // Both {version} and :id are detected

openapi

Only processes OpenAPI/Swagger style parameters ({param}).

'/api/{version}/users/{id}' // Only {version} and {id} are processed
'/api/{version}/users/:id' // Only {version} is processed, :id is ignored

h3

Only processes H3/Nuxt/Express style parameters (:param).

'/users/:userId/posts/:postId' // Only :userId and :postId are processed
'/users/{userId}/posts/:postId' // Only :postId is processed, {userId} is ignored

Error Handling

The library provides clear error messages for common issues:

// Missing parameter
bindUrlTemplateParams('/users/{userId}', {})
// Throws: "Route parameter 'userId' not found in the provided object."

// Null/undefined values
bindUrlTemplateParams('/users/{userId}', { userId: null })
// Throws: "The value for the route parameter 'userId' cannot be null or undefined."

Use Cases

REST API Clients

const apiClient = ofetch.create({
  baseURL: 'https://api.example.com',
  onRequest: bindRequestParamsHook()
})

// Clean, template-based API calls
await apiClient('/users/{userId}', { params: { userId: '123' } })
await apiClient('/posts/{postId}/comments', { params: { postId: '456' } })

Dynamic Route Building

function buildRoute(template: string, params: Record<string, any>) {
  return bindUrlTemplateParams(template, params)
}

const userProfileUrl = buildRoute('/users/{userId}/profile', { userId: 'john' })
const productUrl = buildRoute('/products/:category/:id', { category: 'electronics', id: '123' })

URL Parameter Extraction

// Extract parameters from current route for API calls
const currentRoute = '/users/123/posts/456?sort=date'
const params = extractRouteParamsFromQuery(currentRoute)
// Use params for subsequent API calls

TypeScript Support

Full TypeScript support with comprehensive type definitions:

import type {
  BindRequestParamsHookOptions,
  ExtractRouteParamsOptions,
  RouteParamMode
} from 'ofetch-utils'

const mode: RouteParamMode = 'auto'
const options: BindRequestParamsHookOptions = { mode }

Sponsors

License

MIT License © Eduardo Barros