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
✔️ Compatible: Support connect/express middleware
✔️ Minimal: Small, tree-shakable and zero-dependency
✔️ Modern: Native promise support
✔️ Extendable: Ships with a set of composable utilities but can be extended
Install
npm install h3
yarn add h3
Usage
import { createServer } from 'http'
import { createApp } from 'h3'
const app = createApp()
app.use('/', () => 'Hello world!')
createServer(app).listen(process.env.PORT || 3000)
Example using listhen for an elegant listener.
import { createApp } from 'h3'
import { listen } from 'listhen'
const app = createApp()
app.use('/', () => 'Hello world!')
listen(app)
Examples
app.use('/api', (req) => ({ url: req.url }))
app.use('/odd', () => 'Is odd!', { match: url => url.substr(1) % 2 })
app.use(() => '<h1>Hello world!</h1>')
app.use('/1', () => '<h1>Hello world!</h1>')
.use('/2', () => '<h1>Goodbye!</h1>')
app.use((req, res, next) => { req.setHeader('X-Foo', 'bar'); next() })
Utilities
Instead of adding helpers to req
and res
, h3 exposes them as composable utilities.
useRawBody(req, encoding?)
useBody(req)
useCookies(req)
useCookie(req, name)
setCookie(res, name, value, opts?)
useQuery(req)
send(res, data, type?)
sendRedirect(res, location, code=302)
appendHeader(res, name, value)
createError({ statusCode, statusMessage, data? }
sendError(res, error, debug?)
defineHandle(handle)
defineMiddleware(middlware)
useMethod(req, default?)
isMethod(req, expected, allowHead?)
assertMethod(req, expected, allowHead?)
👉 You can learn more about usage in JSDocs Documentation.
How it works?
Using createApp
, it returns a standard (req, res)
handler function and internally an array called middleware stack. usinguse()
method we can add an item to this internal stack.
When a request comes, each stack item that matches the route will be called and resolved until res.writableEnded
flag is set, which means the response is sent. If writableEnded
is not set after all middleware, a 404
error will be thrown. And if one of the stack items resolves to a value, it will be serialized and sent as response as a shorthand method to sending responses.
For maximum compatibility with connect/express middleware (req, res, next?
signature), h3 converts classic middleware into a promisified version ready to use with stack runner:
- If middleware has 3rd next/callback param, the promise will
resolve/reject
when called - If middleware returns a promise, it will be chained to the main promise
- If calling middleware throws an immediate error, the promise will be rejected
- On
close
and error
events of res, the promise will resolve/reject
(to ensure if middleware simply calls res.end
)
License
MIT