H3

Minimal H(TTP) framework built for high performance and portability

README

H3


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

👉 Online Playground

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


  1. ```bash
  2. # Using npm
  3. npm install h3

  4. # Using yarn
  5. yarn add h3

  6. # Using pnpm
  7. pnpm add h3
  8. ```

Using Nightly Releases

If you are directly using h3 as a dependency:

  1. ```json
  2. {
  3.   "dependencies": {
  4.     "h3": "npm:h3-nightly@latest"
  5.   }
  6. }
  7. ```

If you are using a framework (Nuxt or Nitro) that is usingh3:

pnpm and yarn:

  1. ```json
  2. {
  3.   "resolutions": {
  4.     "h3": "npm:h3-nightly@latest"
  5.   }
  6. }
  7. ```

npm:

  1. ```json
  2. {
  3.   "overrides": {
  4.     "h3": "npm:h3-nightly@latest"
  5.   }
  6. }
  7. ```

Note: Make sure to recreate lockfile and node_modules after reinstall to avoid hoisting issues.


Usage


  1. ```ts
  2. import { createServer } from "node:http";
  3. import { createApp, eventHandler, toNodeListener } from "h3";

  4. const app = createApp();
  5. app.use(
  6.   "/",
  7.   eventHandler(() => "Hello world!"),
  8. );

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

Example using listhen for an elegant listener:

  1. ```ts
  2. import { createApp, eventHandler, toNodeListener } from "h3";
  3. import { listen } from "listhen";

  4. const app = createApp();
  5. app.use(
  6.   "/",
  7.   eventHandler(() => "Hello world!"),
  8. );

  9. listen(toNodeListener(app));
  10. ```

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.

  1. ```ts
  2. import { createApp, eventHandler, createRouter } from "h3";

  3. const app = createApp();

  4. const router = createRouter()
  5.   .get(
  6.     "/",
  7.     eventHandler(() => "Hello World!"),
  8.   )
  9.   .get(
  10.     "/hello/:name",
  11.     eventHandler((event) => `Hello ${event.context.params.name}!`),
  12.   );

  13. app.use(router);
  14. ```

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.

For using nested routers, see this example

More app usage examples


  1. ```js
  2. // Handle can directly return object or Promise for JSON response
  3. app.use(
  4.   "/api",
  5.   eventHandler((event) => ({ url: event.node.req.url })),
  6. );

  7. // We can have better matching other than quick prefix match
  8. app.use(
  9.   "/odd",
  10.   eventHandler(() => "Is odd!"),
  11.   { match: (url) => url.substr(1) % 2 },
  12. );

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

  15. // We can chain calls to .use()
  16. app
  17.   .use(
  18.     "/1",
  19.     eventHandler(() => "<h1>Hello world!</h1>"),
  20.   )
  21.   .use(
  22.     "/2",
  23.     eventHandler(() => "<h1>Goodbye!</h1>"),
  24.   );

  25. // We can proxy requests and rewrite cookie's domain and path
  26. app.use(
  27.   "/api",
  28.   eventHandler((event) =>
  29.     proxyRequest(event, "https://example.com", {
  30.       // f.e. keep one domain unchanged, rewrite one domain and remove other domains
  31.       cookieDomainRewrite: {
  32.         "example.com": "example.com",
  33.         "example.com": "somecompany.co.uk",
  34.         "*": "",
  35.       },
  36.       cookiePathRewrite: {
  37.         "/": "/api",
  38.       },
  39.     }),
  40.   ),
  41. );

  42. // Legacy middleware with 3rd argument are automatically promisified
  43. app.use(
  44.   fromNodeMiddleware((req, res, next) => {
  45.     req.setHeader("x-foo", "bar");
  46.     next();
  47.   }),
  48. );

  49. // Lazy loaded routes using { lazy: true }
  50. app.use("/big", () => import("./big-handler"), { lazy: true });
  51. ```

  52. 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.

    👉 You can check list of exported built-in utils from JSDocs Documentation.

    Body


    - readRawBody(event, encoding?)
    - readBody(event)
    - readValidatedBody(event, validate)
    - readMultipartFormData(event)

    Request


    - getQuery(event)
    - getValidatedQuery(event, validate)
    - getRouterParams(event)
    - getMethod(event, default?)
    - isMethod(event, expected, allowHead?)
    - assertMethod(event, expected, allowHead?)
    - getRequestHeaders(event, headers) (alias: getHeaders)
    - getRequestHeader(event, name) (alias: getHeader)
    - getRequestURL(event)
    - getRequestHost(event)
    - getRequestProtocol(event)
    - getRequestPath(event)
    - getRequestIP(event, { xForwardedFor: boolean })

    Response


    - send(event, data, type?)
    - sendNoContent(event, code = 204)
    - setResponseStatus(event, status)
    - getResponseStatus(event)
    - getResponseStatusText(event)
    - getResponseHeaders(event)
    - getResponseHeader(event, name)
    - setResponseHeaders(event, headers) (alias: setHeaders)
    - setResponseHeader(event, name, value) (alias: setHeader)
    - appendResponseHeaders(event, headers) (alias: appendHeaders)
    - appendResponseHeader(event, name, value) (alias: appendHeader)
    - defaultContentType(event, type)
    - sendRedirect(event, location, code=302)
    - isStream(data)
    - sendStream(event, data)
    - writeEarlyHints(event, links, callback)

    Sanitize


    - sanitizeStatusMessage(statusMessage)
    - sanitizeStatusCode(statusCode, default = 200)

    Error


    - sendError(event, error, debug?)
    - createError({ statusCode, statusMessage, data? })

    Route


    - useBase(base, handler)

    Proxy


    - sendProxy(event, { target, ...options })
    - proxyRequest(event, { target, ...options })
    - fetchWithEvent(event, req, init, { fetch? }?)
    - getProxyRequestHeaders(event)

    Cookie


    - parseCookies(event)
    - getCookie(event, name)
    - setCookie(event, name, value, opts?)
    - deleteCookie(event, name, opts?)
    - splitCookiesString(cookiesString)

    Session


    - useSession(event, config = { password, maxAge?, name?, cookie?, seal?, crypto? })
    - getSession(event, config)
    - updateSession(event, config, update)
    - sealSession(event, config)
    - unsealSession(event, config, sealed)
    - clearSession(event, config)

    Cache


    - handleCacheHeaders(event, opts)

    Cors


    - 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)

    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.

      - validateBody(event, schema)
      - validateQuery(event, schema)
      - useValidatedBody(event, schema)
      - useValidatedQuery(event, schema)
      - useValidateBody(event, schema)
      - useValidateParams(event, schema)