What is h3?
The h3 npm package is a high-performance HTTP framework for Node.js, designed to be lightweight and fast. It is often used for building APIs and microservices, providing a simple and efficient way to handle HTTP requests and responses.
What are h3's main functionalities?
Basic HTTP Server
This code demonstrates how to create a basic HTTP server using the h3 package. The server listens on port 3000 and responds with 'Hello, world!' to any incoming requests.
const { createApp } = require('h3');
const { createServer } = require('http');
const app = createApp();
app.use('/', (req, res) => {
res.end('Hello, world!');
});
createServer(app).listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Middleware Support
This example shows how to use middleware with the h3 package. The middleware logs each incoming request's method and URL before passing control to the next handler.
const { createApp } = require('h3');
const { createServer } = require('http');
const app = createApp();
// Middleware to log requests
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
app.use('/', (req, res) => {
res.end('Hello, world!');
});
createServer(app).listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Routing
This code demonstrates how to set up routing with the h3 package. It defines GET and POST routes for the '/hello' path, responding with different messages based on the HTTP method.
const { createApp, useRouter } = require('h3');
const { createServer } = require('http');
const app = createApp();
const router = useRouter();
router.get('/hello', (req, res) => {
res.end('Hello, GET!');
});
router.post('/hello', (req, res) => {
res.end('Hello, POST!');
});
app.use(router);
createServer(app).listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Other packages similar to h3
express
Express is a widely-used web application framework for Node.js, known for its simplicity and flexibility. It provides robust routing, middleware support, and a wide range of HTTP utility methods. Compared to h3, Express is more feature-rich and has a larger community, but it may be heavier and less performant for certain use cases.
koa
Koa is a next-generation web framework for Node.js, created by the same team behind Express. It uses async functions to simplify middleware and improve error handling. Koa is more modular and lightweight compared to Express, similar to h3, but it requires more boilerplate code to set up.
fastify
Fastify is a web framework for Node.js that focuses on performance and low overhead. It provides a schema-based validation system and a powerful plugin architecture. Fastify is similar to h3 in terms of performance and simplicity, but it offers more built-in features and a more extensive plugin ecosystem.
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
npm install h3
yarn add h3
pnpm add h3
Usage
import { createServer } from 'http'
import { createApp, eventHandler } 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, 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 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
app.use('/api', eventHandler((event) => ({ url: event.req.url }))
app.use('/odd', eventHandler(() => 'Is odd!'), { match: url => url.substr(1) % 2 })
app.use(eventHandler(() => '<h1>Hello world!</h1>'))
app.use('/1', eventHandler(() => '<h1>Hello world!</h1>'))
.use('/2', eventHandler(() => '<h1>Goodbye!</h1>'))
app.use(fromNodeMiddleware((req, res, next) => { req.setHeader('x-foo', 'bar'); next() }))
app.use('/big', () => import('./big-handler'), { lazy: true })
Utilities
H3 has concept of compasable utilities that accept event
(from eventHandler((event) => {})
) as their first argument. This has several performance benefits over injecting them to event
or app
instances and global middleware commonly used in Node.js frameworks such as Express, which Only required code is evaluated and bundled and rest of utils can be tree-shaken when not used.
Built-in
useRawBody(event, encoding?)
useBody(event)
useCookies(event)
useCookie(event, name)
setCookie(event, name, value, opts?)
deleteCookie(event, name, opts?)
useQuery(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?)
useMethod(event, default?)
isMethod(event, expected, allowHead?)
assertMethod(event, expected, allowHead?)
createError({ statusCode, statusMessage, data? })
sendProxy(event, { target, headers?, fetchOptions?, fetch?, sendStream? })
👉 You can learn more about usage in JSDocs Documentation.
Add-ons
More composable utilities can be found in community packages.
License
MIT