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.
What?
- Works perfectly with Serverless, Workers and NodeJS
- Compatible with connect/express middleware
- Tree-shakable and zero-dependency
- Promise and
aync/await
support - Lazy loading
- Quick prefix router
- Custom route matcher
See un for workers support
Install
yarn add h3
npm install h3
Usage
Using listhen:
const { createApp } = require('h3')
const { listen } = require('listhen')
const app = createApp()
app.use('/', () => 'Hello world!')
listhen(app)
Using plain node:
const { Server } = require('http')
const { createApp } = require('h3')
const app = createApp()
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>')
const port = process.env.PORT || 3000
const server = new Server(app)
server.listen(port, () => {
console.log(`Listening on: http://localhost:${port}`)
})
Technical
There are two vital parts that make it working: Stack Runner (App
), and promisifyHandle
.
App
App is basically a http server handle with req, res
and attached utilities that runs a stack
of middleware/handles in parallel. It will stop when the writableEnded
flag is set on a response
(which means that res.end
has been called) and throw a 404 if writableEnded
flag has not been set by the end.
Additionally the app has a quick prefix matcher and will automatically call res.end
if any stack layers return a value.
promisifyHandle
Converts a classic middleware (req, res, next?
) into a promisified version ready to use with App
- If middleware has 3rd next/callback param, promise will
resolve/reject
when called - If middleware returns a promise, it will be chained to main promise
- If calling middleware throws an immediate error, promise will be rejected
- On
close
and error
events of res, promise will resolve/reject
(to ensure if middleware simply calls res.end
)
When calling app.use
, middleware will be automatically promisified.
If you are already making an async aware middleware, you can use app.useAsync
License
MIT