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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@hebilicious/h3

v0.0.4

Published

Fork of unjs/h3

Downloads

6

Readme

H3

npm version npm downloads bundle Codecov License JSDocs

H3 is a minimal h(ttp) framework built for high performance and portability.

Features

✔️  Portable: Works perfectly in Serverless, Workers, and Node.js

✔️  Minimal: Small and tree-shakable

✔️  Modern: Native promise support

✔️  Extendable: Ships with a set of composable utilities but can be extended

✔️  Router: Super fast route matching using unjs/radix3

✔️  Compatible: Compatibility layer with node/connect/express middleware

Install

# Using npm
npm install h3

# Using yarn
yarn add h3

# Using pnpm
pnpm add h3

Usage

import { createServer } from "node:http";
import { createApp, eventHandler, toNodeListener } from "h3";

const app = createApp();
app.use(
  "/",
  eventHandler(() => "Hello world!")
);

createServer(toNodeListener(app)).listen(process.env.PORT || 3000);

Example using listhen for an elegant listener:

import { createApp, eventHandler, toNodeListener } from "h3";
import { listen } from "listhen";

const app = createApp();
app.use(
  "/",
  eventHandler(() => "Hello world!")
);

listen(toNodeListener(app));

Router

The app instance created by h3 uses a middleware stack (see how it works) with the ability to match route prefix and apply matched middleware.

To opt-in using a more advanced and convenient routing system, we can create a router instance and register it to app instance.

import { createApp, eventHandler, createRouter } from "h3";

const app = createApp();

const router = createRouter()
  .get(
    "/",
    eventHandler(() => "Hello World!")
  )
  .get(
    "/hello/:name",
    eventHandler((event) => `Hello ${event.context.params.name}!`)
  );

app.use(router);

Tip: We can register the same route more than once with different methods.

Routes are internally stored in a Radix Tree and matched using unjs/radix3.

More app usage examples

// Handle can directly return object or Promise<object> for JSON response
app.use('/api', eventHandler((event) => ({ url: getUrlPath(event) })))

// We can have better matching other than quick prefix match
app.use('/odd', eventHandler(() => 'Is odd!'), { match: url => url.substr(1) % 2 })

// Handle can directly return string for HTML response
app.use(eventHandler(() => '<h1>Hello world!</h1>'))

// We can chain calls to .use()
app.use('/1', eventHandler(() => '<h1>Hello world!</h1>'))
   .use('/2', eventHandler(() => '<h1>Goodbye!</h1>'))

// We can proxy requests and rewrite cookie's domain and path
app.use('/api', eventHandler((event) => proxyRequest(event, 'https://example.com', {
  // f.e. keep one domain unchanged, rewrite one domain and remove other domains
  cookieDomainRewrite: {
    "example.com": "example.com",
    "example.com": "somecompany.co.uk",
    "*": "",
  },
  cookiePathRewrite: {
    "/": "/api"
  },
})))

// Legacy middleware with 3rd argument are automatically promisified
app.use(fromNodeMiddleware((req, res, next) => { req.setHeader('x-foo', 'bar'); next() }))

// Lazy loaded routes using { lazy: true }
app.use('/big', () => import('./big-handler'), { lazy: true })

Utilities

H3 has a concept of composable utilities that accept event (from eventHandler((event) => {})) as their first argument. This has several performance benefits over injecting them to event or app instances in global middleware commonly used in Node.js frameworks, such as Express. This concept means only required code is evaluated and bundled, and the rest of the utilities can be tree-shaken when not used.

Built-in

  • readRawBody(event, encoding?)
  • readBody(event)
  • parseCookies(event)
  • getCookie(event, name)
  • setCookie(event, name, value, opts?)
  • deleteCookie(event, name, opts?)
  • getQuery(event)
  • getRouterParams(event)
  • send(event, data, type?)
  • sendRedirect(event, location, code=302)
  • getRequestHeaders(event, headers) (alias: getHeaders)
  • getRequestHeader(event, name) (alias: getHeader)
  • setResponseHeaders(event, headers) (alias: setHeaders)
  • setResponseHeader(event, name, value) (alias: setHeader)
  • appendResponseHeaders(event, headers) (alias: appendHeaders)
  • appendResponseHeader(event, name, value) (alias: appendHeader)
  • writeEarlyHints(event, links, callback)
  • sendStream(event, data)
  • sendError(event, error, debug?)
  • getMethod(event, default?)
  • isMethod(event, expected, allowHead?)
  • assertMethod(event, expected, allowHead?)
  • createError({ statusCode, statusMessage, data? })
  • sendProxy(event, { target, ...options })
  • proxyRequest(event, { target, ...options })
  • fetchWithEvent(event, req, init, { fetch? }?)
  • getProxyRequestHeaders(event)
  • sendNoContent(event, code = 204)
  • setResponseStatus(event, status)
  • getResponseStatus(event)
  • getResponseStatusText(event)
  • readMultipartFormData(event)
  • useSession(event, config = { password, maxAge?, name?, cookie?, seal?, crypto? })
  • getSession(event, config)
  • updateSession(event, config, update)
  • clearSession(event, config)
  • sealSession(event, config)
  • unsealSession(event, config, sealed)
  • handleCors(options) (see h3-cors for more detail about options)
  • isPreflightRequest(event)
  • isCorsOriginAllowed(event)
  • appendCorsHeaders(event, options) (see h3-cors for more detail about options)
  • appendCorsPreflightHeaders(event, options) (see h3-cors for more detail about options)
  • getRequestHost(event)
  • getRequestProtocol(event)
  • getRequestURL(event)

👉 You can learn more about usage in JSDocs Documentation.

Community Packages

You can use more H3 event utilities made by the community.

Please check their READMEs for more details.

PRs are welcome to add your packages.

  • h3-typebox
    • validateBody(event, schema)
    • validateQuery(event, schema)
  • h3-zod
    • useValidatedBody(event, schema)
    • useValidatedQuery(event, schema)

License

MIT