Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
H3
https://github.com/zhcndoc/h3
Admin
H3 中文文档
Tokens:
1,633
Snippets:
19
Trust Score:
6.9
License:
MIT
Update:
1 year ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### H3 Local Development Setup Commands Source: https://github.com/zhcndoc/h3/blob/main/README.md A collection of shell commands required to set up and run the H3 project for local development. This includes enabling Corepack, installing project dependencies, and executing development and test scripts. ```shell corepack enable ``` ```shell pnpm install ``` ```shell pnpm dev ``` ```shell pnpm test ``` -------------------------------- ### Create Basic H3 Plugins as Functions Source: https://github.com/zhcndoc/h3/blob/main/docs/1.guide/901.advanced/1.plugins.md This example illustrates the fundamental structure of an H3 plugin. A plugin is simply a function that accepts an H3 instance as its first argument, allowing it to immediately apply logic and extend the application's functionality. ```js app.register((app) => { app.use(...) }) ``` -------------------------------- ### Get All Router Parameters (getRouterParams) Source: https://github.com/zhcndoc/h3/blob/main/docs/2.utils/1.request.md Retrieves a collection of all matched router parameters. If the `decode` option is true, all matched router parameters will be decoded using `decodeURIComponent`. ```ts app.get("/", (event) => { const params = getRouterParams(event); // { key: "value" } }); ``` -------------------------------- ### Get Full Request URL (getRequestURL) Source: https://github.com/zhcndoc/h3/blob/main/docs/2.utils/1.request.md Generates the complete incoming request URL. If `xForwardedHost` is true, it uses the `x-forwarded-host` request header if present. If `xForwardedProto` is false, it does not use the `x-forwarded-proto` request header. ```ts app.get("/", (event) => { const url = getRequestURL(event); // "https://example.com/path" }); ``` -------------------------------- ### Get Query Parameters (getQuery) Source: https://github.com/zhcndoc/h3/blob/main/docs/2.utils/1.request.md Retrieves the parsed query string object from the request URL. ```ts app.get("/", (event) => { const query = getQuery(event); // { key: "value", key2: ["value1", "value2"] } }); ``` -------------------------------- ### Get Request Host (getRequestHost) Source: https://github.com/zhcndoc/h3/blob/main/docs/2.utils/1.request.md Retrieves the request hostname. If `xForwardedHost` is true, it prioritizes the `x-forwarded-host` request header if present. Defaults to "localhost" if no host header is found. ```ts app.get("/", (event) => { const host = getRequestHost(event); // "example.com" }); ``` -------------------------------- ### Register H3 Plugins with Instance Config or `register` Method Source: https://github.com/zhcndoc/h3/blob/main/docs/1.guide/901.advanced/1.plugins.md This snippet demonstrates two ways to register plugins in an H3 application: either by providing them in the configuration object during H3 instance creation or by using the `app.register()` method on an existing instance. It shows an example with a 'logger' plugin. ```js import { H3 } from "h3"; import { logger } from "./logger.mjs"; // Using instance config const app = new H3({ plugins: [logger()] }); // Or register later app.register(logger()); // ... rest of the code.. app.get("/**", () => "Hello, World!"); ``` -------------------------------- ### Get Request Protocol (getRequestProtocol) Source: https://github.com/zhcndoc/h3/blob/main/docs/2.utils/1.request.md Retrieves the request protocol. If the `x-forwarded-proto` request header is "https", it returns "https". This behavior can be disabled by setting `xForwardedProto` to `false`. Defaults to "http" if the protocol cannot be determined. ```ts app.get("/", (event) => { const protocol = getRequestProtocol(event); // "https" }); ``` -------------------------------- ### Check Request Method (isMethod) Source: https://github.com/zhcndoc/h3/blob/main/docs/2.utils/1.request.md Checks if the incoming request method matches the expected type. If `allowHead` is true and the expected method is `GET`, `HEAD` requests are also permitted. ```ts app.get("/", (event) => { if (isMethod(event, "GET")) { // Handle GET request } else if (isMethod(event, ["POST", "PUT"])) { // Handle POST or PUT request } }); ``` -------------------------------- ### Get Request Fingerprint (getRequestFingerprint) Source: https://github.com/zhcndoc/h3/blob/main/docs/2.utils/1.request.md Retrieves a unique fingerprint for the incoming request. ```APIDOC getRequestFingerprint(event, opts) event: The H3 event object. opts: Options for fingerprint generation. ``` -------------------------------- ### Get Single Router Parameter (getRouterParam) Source: https://github.com/zhcndoc/h3/blob/main/docs/2.utils/1.request.md Retrieves a matched router parameter by name. If the `decode` option is true, the matched router parameter will be decoded using `decodeURI`. ```ts app.get("/", (event) => { const param = getRouterParam(event, "key"); }); ``` -------------------------------- ### Assert Request Method (assertMethod) Source: https://github.com/zhcndoc/h3/blob/main/docs/2.utils/1.request.md Asserts that the incoming request method matches the expected type using `isMethod`. If the request method is not allowed, it throws a 405 error with the message "HTTP method is not allowed". If `allowHead` is true and the expected method is `GET`, `HEAD` requests are also permitted. ```ts app.get("/", (event) => { assertMethod(event, "GET"); // Handle GET request, otherwise a 405 error is thrown }); ``` -------------------------------- ### Get Request IP Address (getRequestIP) Source: https://github.com/zhcndoc/h3/blob/main/docs/2.utils/1.request.md Attempts to retrieve the client IP address from the incoming request. If `xForwardedFor` is true, it prioritizes the `x-forwarded-for` request header if present. Returns `undefined` if the IP cannot be determined. ```ts app.get("/", (event) => { const ip = getRequestIP(event); // "192.0.2.0" }); ``` -------------------------------- ### Get and Validate Router Parameters (getValidatedRouterParams) Source: https://github.com/zhcndoc/h3/blob/main/docs/2.utils/1.request.md Retrieves matched router parameters and validates them using a provided validation function. If the `decode` option is true, matched router parameters will be decoded using `decodeURI`. You can use a simple function to validate the parameter object, or a schema-compatible library like Zod to define the schema. ```ts app.get("/", async (event) => { const params = await getValidatedRouterParams(event, (data) => { return "key" in data && typeof data.key === "string"; }); }); ``` ```ts import { z } from "zod"; app.get("/", async (event) => { const params = await getValidatedRouterParams( event, z.object({ key: z.string(), }), ); }); ``` -------------------------------- ### Get and Validate Query Parameters (getValidatedQuery) Source: https://github.com/zhcndoc/h3/blob/main/docs/2.utils/1.request.md Retrieves and validates request URL query parameters using a provided validation function or schema. You can use a simple function to validate the query object, or a schema-compatible library like Zod to define the schema. ```ts app.get("/", async (event) => { const query = await getValidatedQuery(event, (data) => { return "key" in data && typeof data.key === "string"; }); }); ``` ```ts import { z } from "zod"; app.get("/", async (event) => { const query = await getValidatedQuery( event, z.object({ key: z.string(), }), ); }); ``` -------------------------------- ### Create Typed H3 Plugins using `definePlugin` Utility Source: https://github.com/zhcndoc/h3/blob/main/docs/1.guide/901.advanced/1.plugins.md This snippet demonstrates how to use H3's built-in `definePlugin` utility to create a typed factory function for plugins. It shows how to include optional plugin-specific options and apply conditional logic, such as a logger that activates based on a debug configuration. ```js import { definePlugin } from "h3"; const logger = definePlugin((h3, _options) => { if (h3.config.debug) { h3.use((req) => { console.log(`[${req.method}] ${req.url}`); }); } }); ``` -------------------------------- ### Handle Cache Headers (handleCacheHeaders) Source: https://github.com/zhcndoc/h3/blob/main/docs/2.utils/1.request.md Checks request cache headers (`If-Modified-Since`) and adds response cache headers (`Last-Modified`, `Cache-Control`). Note: `public` cache control is added by default. ```APIDOC handleCacheHeaders(event, opts) event: The H3 event object. opts: Options for cache headers. ``` -------------------------------- ### Read and Validate Request Body (readValidatedBody) Source: https://github.com/zhcndoc/h3/blob/main/docs/2.utils/1.request.md Attempts to read the request body using `readBody`, then validates it with a provided schema or function. Throws an error on validation failure, returns the result on success. You can use a simple function for validation or a schema-compatible library like Zod. ```ts app.get("/", async (event) => { const body = await readValidatedBody(event, (body) => { return typeof body === "object" && body !== null; }); }); ``` ```ts import { z } from "zod"; app.get("/", async (event) => { const objectSchema = z.object({ name: z.string().min(3).max(20), age: z.number({ coerce: true }).positive().int(), }); const body = await readValidatedBody(event, objectSchema); }); ``` -------------------------------- ### Read Request Body (readBody) Source: https://github.com/zhcndoc/h3/blob/main/docs/2.utils/1.request.md Reads the request body and attempts to parse it as JSON or URLSearchParams. ```ts app.get("/", async (event) => { const body = await readBody(event); }); ```