Security News
Introducing the Socket Python SDK
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
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.
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');
});
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 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 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.
✔️ 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
# Using npm
npm install h3
# Using yarn
yarn add h3
# Using pnpm
pnpm add h3
If you are directly using h3
as a dependency:
{
"dependencies": {
"h3": "npm:h3-nightly@latest"
}
}
If you are using a framework (Nuxt or Nitro) that is using h3
:
pnpm and yarn:
{
"resolutions": {
"h3": "npm:h3-nightly@latest"
}
}
npm:
{
"overrides": {
"h3": "npm:h3-nightly@latest"
}
}
Note: Make sure to recreate lockfile and node_modules
after reinstall to avoid hoisting issues.
import { createServer } from "node:http";
import { createApp, eventHandler, toNodeListener } 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, eventHandler, toNodeListener } from "h3";
import { listen } from "listhen";
const app = createApp();
app.use(
"/",
eventHandler(() => "Hello world!"),
);
listen(toNodeListener(app));
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 the same route more than once with different methods.
Routes are internally stored in a Radix Tree and matched using unjs/radix3.
For using nested routers, see this example
// Handle can directly return object or Promise<object> for JSON response
app.use(
"/api",
eventHandler((event) => ({ url: event.node.req.url })),
);
// We can have better matching other than quick prefix match
app.use(
"/odd",
eventHandler(() => "Is odd!"),
{ match: (url) => url.substr(1) % 2 },
);
// Handle can directly return string for HTML response
app.use(eventHandler(() => "<h1>Hello world!</h1>"));
// We can chain calls to .use()
app
.use(
"/1",
eventHandler(() => "<h1>Hello world!</h1>"),
)
.use(
"/2",
eventHandler(() => "<h1>Goodbye!</h1>"),
);
// We can proxy requests and rewrite cookie's domain and path
app.use(
"/api",
eventHandler((event) =>
proxyRequest(event, "https://example.com", {
// f.e. keep one domain unchanged, rewrite one domain and remove other domains
cookieDomainRewrite: {
"example.com": "example.com",
"example.com": "somecompany.co.uk",
"*": "",
},
cookiePathRewrite: {
"/": "/api",
},
}),
),
);
// Legacy middleware with 3rd argument are automatically promisified
app.use(
fromNodeMiddleware((req, res, next) => {
req.setHeader("x-foo", "bar");
next();
}),
);
// Lazy loaded routes using { lazy: true }
app.use("/big", () => import("./big-handler"), { lazy: true });
H3 has a concept of composable utilities that accept event
(from eventHandler((event) => {})
) as their first argument. This has several performance benefits over injecting them to event
or app
instances in global middleware commonly used in Node.js frameworks, such as Express. This concept means only required code is evaluated and bundled, and the rest of the utilities can be tree-shaken when not used.
👉 You can check list of exported built-in utils from JSDocs Documentation.
readRawBody(event, encoding?)
readBody(event)
readValidatedBody(event, validate)
readMultipartFormData(event)
getQuery(event)
getValidatedQuery(event, validate)
getRouterParams(event)
getMethod(event, default?)
isMethod(event, expected, allowHead?)
assertMethod(event, expected, allowHead?)
getRequestHeaders(event, headers)
(alias: getHeaders
)getRequestHeader(event, name)
(alias: getHeader
)getRequestURL(event)
getRequestHost(event)
getRequestProtocol(event)
getRequestPath(event)
getRequestIP(event, { xForwardedFor: boolean })
send(event, data, type?)
sendNoContent(event, code = 204)
setResponseStatus(event, status)
getResponseStatus(event)
getResponseStatusText(event)
getResponseHeaders(event)
getResponseHeader(event, name)
setResponseHeaders(event, headers)
(alias: setHeaders
)setResponseHeader(event, name, value)
(alias: setHeader
)appendResponseHeaders(event, headers)
(alias: appendHeaders
)appendResponseHeader(event, name, value)
(alias: appendHeader
)defaultContentType(event, type)
sendRedirect(event, location, code=302)
isStream(data)
sendStream(event, data)
writeEarlyHints(event, links, callback)
sanitizeStatusMessage(statusMessage)
sanitizeStatusCode(statusCode, default = 200)
sendError(event, error, debug?)
createError({ statusCode, statusMessage, data? })
useBase(base, handler)
sendProxy(event, { target, ...options })
proxyRequest(event, { target, ...options })
fetchWithEvent(event, req, init, { fetch? }?)
getProxyRequestHeaders(event)
parseCookies(event)
getCookie(event, name)
setCookie(event, name, value, opts?)
deleteCookie(event, name, opts?)
splitCookiesString(cookiesString)
useSession(event, config = { password, maxAge?, name?, cookie?, seal?, crypto? })
getSession(event, config)
updateSession(event, config, update)
sealSession(event, config)
unsealSession(event, config, sealed)
clearSession(event, config)
handleCacheHeaders(event, opts)
handleCors(options)
(see h3-cors for more detail about options)isPreflightRequest(event)
isCorsOriginAllowed(event)
appendCorsHeaders(event, options)
(see h3-cors for more detail about options)appendCorsPreflightHeaders(event, options)
(see h3-cors for more detail about options)You can use more H3 event utilities made by the community.
Please check their READMEs for more details.
PRs are welcome to add your packages.
validateBody(event, schema)
validateQuery(event, schema)
useValidatedBody(event, schema)
useValidatedQuery(event, schema)
useValidateBody(event, schema)
useValidateParams(event, schema)
MIT
v1.8.1
Headers
and Response
for legacy polyfills (#523)FAQs
Minimal H(TTP) framework built for high performance and portability.
The npm package h3 receives a total of 905,025 weekly downloads. As such, h3 popularity was classified as popular.
We found that h3 demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
Security News
Floating dependency ranges in npm can introduce instability and security risks into your project by allowing unverified or incompatible versions to be installed automatically, leading to unpredictable behavior and potential conflicts.
Security News
A new Rust RFC proposes "Trusted Publishing" for Crates.io, introducing short-lived access tokens via OIDC to improve security and reduce risks associated with long-lived API tokens.