Getting Started
Overview
h3 (short for HTTP, pronounced as /eɪtʃθriː/, like h-3) is a lightweight, ultra fast and composable server framework for JavaScript based on Web standards working on any JavaScript runtime.
Quick Start
Install h3
as a dependency:
npm i h3
Create a new file server.mjs
:
import { H3, serve } from "h3";
const app = new H3();
app.get("/", () => "⚡️ Tadaa!");
await serve(app, { port: 3000 })
.ready()
.then((server) => {
console.log(`🚀 Server ready at ${server.url}`);
});
Then, run the server using your favorite runtime:
node --watch ./server.mjs
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 h3 app instance using new H3()
:
const app = new H3(/* optional config */);
app
is a tiny server capable of matching routes, generating response and handling lifecycle hooks such as errors.
Then we create register a route for handling HTTP GET requests to /
path.
app.get("/", () => {
return { message: "⚡️ Tadaa!" };
});
In h3 event handlers, all you have to do to make a response, is to simply return it! Responses can be simple string, JSON object, binary data, stream, error, ... or standard Web Response.
Finally we use serve
method to start the server listener.
Based on runtime and export conditions, correct adapter will be auto loaded.
You can also directly export or use
app.fetch(request)
.Using 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 { H3, toWebHandler } from "https://esm.sh/h3";
const app = new H3();
export const fetch = app.fetch;
Run and deploy
Using serve(app, options?)
you can easily run h3 apps in Deno, Node.js and Bun runtimes.
With the main h3 app instance you have app.fetch
which can be directly used to run h3 apps in any web-compatible runtime or even directly called for testing purposes.
import { H3, serve } from "h3";
const app = new H3().get("/", () => "⚡️ Tadaa!");
// Test without listening
const response = await app.fetch("/");
console.log(await response.text());