Getting Started

Getting started with h3


Overview

h3 (short for HTTP, pronounced as /eɪtʃθriː/, like h-3) is a lightweight and composable server framework for JavaScript that is designed to work with various javascript runtimes through adapters.

Check out Nitro for a full featured server toolkit.

Quick Start

Create a new file app.ts (or app.js):

app.ts
// Import h3 as npm dependency
import { createApp, createRouter, defineEventHandler } from "h3";

// Create an app instance
export const app = createApp();

// Create a new router and register it in app
const router = createRouter();
app.use(router);

// Add a new route that matches GET requests to / path
router.get(
  "/",
  defineEventHandler((event) => {
    return { message: "⚡️ Tadaa!" };
  }),
);

Now run the development server using unjs/listhen:

npx --yes listhen -w --open ./app.ts
You don't need to install any additional dependency. Listhen has a preinstalled version of h3!

And tadaa! We have a web server running locally.

What happened?

Okay, let's now break down our hello world example:

We first created an app instance using createApp(). app is a tiny server capable of matching requests, generating response and handling lifecycle hooks (such as errors):

export const app = createApp();

Then we create a router instance that can match route patterns and http methods using unjs/radix3 and register it for app as main handler:

const router = createRouter();

app.use(router);

Now it is time to add our first endpoint. In h3, request handlers can be defined using defineEventHandler or eventHandler helpers (they are aliases). Using wrappers, h3 can supercharge your code with better typehints and future compatibility.

defineEventHandler((event) => {});

What is beautiful in h3 is that all you have to do to make a reponse, is to simply return it! Responses can be simple string, JSON objects, data buffers, streams or standard Web Response.

return { message: "⚡️ Tadaa!" };

Finally, we use unjs/listhen CLI using npx to auto install it. Listhen will automatically setup and start our webserver with zero configuration and adds on-the-fly TypeScript support to your experience!

Installing h3

You can import h3 either as an npm package or from CDN.

Install as npm package

You can use this method for Node.js and Bun.

npm i h3

Import from CDN

You can directly import h3 from CDN. This method can be used for Bun, Deno and other runtimes such as Cloudflare Workers (you need an adapter).

import { createApp, toWebHandler } from "https://esm.sh/h3";

export const app = createApp();

export const handler = toWebHandler(app);