Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

initialize docs #595

Merged
merged 51 commits into from
Feb 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
3caa6a7
chore: initialize docs
pi0 Dec 7, 2023
4a2a492
update landing and theme
pi0 Dec 7, 2023
07f8d76
lint
pi0 Dec 7, 2023
5fb63b3
add runtimes and more updates
pi0 Dec 7, 2023
142fe0c
update
pi0 Dec 7, 2023
4112ade
fix 404 links
pi0 Dec 7, 2023
14fb900
make landing example little shorter
pi0 Dec 7, 2023
049ff12
set light theme
pi0 Dec 8, 2023
63ade75
chore: update deps
Barbapapazes Dec 29, 2023
b18485a
feat: update design
Barbapapazes Dec 29, 2023
2db59d7
chore: update deps
Barbapapazes Dec 29, 2023
977da9e
chore: update meta
atinux Jan 12, 2024
8373e22
feat: move to unjs/docs (#629)
Barbapapazes Jan 25, 2024
b0c2cc7
docs: update the event handler page (#633)
Barbapapazes Jan 25, 2024
9e85556
docs: update the event page (#634)
Barbapapazes Jan 25, 2024
9bd1781
docs: add middleware page (#635)
Barbapapazes Jan 25, 2024
18a4e74
docs: update utilities page (#637)
Barbapapazes Jan 25, 2024
6d7ebc9
docs: update installation page (#638)
Barbapapazes Jan 25, 2024
b4f8ef8
docs: create a validate-data guide (#639)
Barbapapazes Jan 25, 2024
e20469a
docs: create handle session guide (#640)
Barbapapazes Jan 25, 2024
e9a4008
docs: update router page (#636)
Barbapapazes Jan 25, 2024
a005662
Merge branch 'main' into docs
pi0 Jan 25, 2024
bd84b89
fix links only to build
pi0 Jan 25, 2024
13e65f1
docs: fix missing `.handler` when using a router
Barbapapazes Jan 26, 2024
b752de3
docs: create from express to h3 article
Barbapapazes Jan 26, 2024
44e8d5c
docs: add some notes to from expressjs to h3
Barbapapazes Jan 26, 2024
752628a
docs: write serve static assets guide
Barbapapazes Jan 26, 2024
9c25afc
docs: use delete-cookie in from express to h3
Barbapapazes Jan 26, 2024
9ccb4c0
docs: add a guide to handle cookie
Barbapapazes Jan 26, 2024
b7a89e7
docs: create the stream guide
Barbapapazes Jan 26, 2024
d1ddf0c
chore: lint and fix
Barbapapazes Jan 26, 2024
eeb730b
fix: alert to caution
Barbapapazes Jan 26, 2024
a10edfd
chore: apply automated fixes
autofix-ci[bot] Jan 26, 2024
b68fc35
docs: update app page (#632)
Barbapapazes Jan 28, 2024
824d965
docs: fix event handler name
Barbapapazes Jan 28, 2024
d1e3fb9
docs: create node adapters
Barbapapazes Jan 28, 2024
987df10
docs: update runtimes
Barbapapazes Jan 28, 2024
35b3488
docs: remove old runtimes
Barbapapazes Jan 28, 2024
55b974c
docs: rework netlify h3 docs
Barbapapazes Jan 28, 2024
e1111d5
docs: update web runtime
Barbapapazes Jan 28, 2024
dd90130
docs: move utils
Barbapapazes Jan 28, 2024
59664a3
docs: create adapters web and plain
Barbapapazes Jan 28, 2024
0a52f76
chore: apply automated fixes
autofix-ci[bot] Jan 28, 2024
12b939d
update to undocs
pi0 Feb 22, 2024
5518143
update
pi0 Feb 22, 2024
3c753ee
update dep
pi0 Feb 22, 2024
988e8c0
update
pi0 Feb 22, 2024
511e151
Merge branch 'main' into docs
pi0 Feb 22, 2024
42c7b69
Merge branch 'main' into docs
pi0 Feb 22, 2024
353a488
cleanup
pi0 Feb 22, 2024
b01058a
cleanup
pi0 Feb 22, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ coverage
.idea
.eslintcache
tsconfig.vitest-temp.json
.DS_Store
307 changes: 0 additions & 307 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,313 +27,6 @@ H3 (pronounced as /eɪtʃθriː/, like h-3) is a minimal h(ttp) framework built

✔️  **Compatible:** Compatibility layer with node/connect/express middleware

## Install

```bash
# Using npm
npm install h3

# Using yarn
yarn add h3

# Using pnpm
pnpm add h3
```

<details>
<summary>Using Nightly Releases</summary>

If you are directly using `h3` as a dependency:

```json
{
"dependencies": {
"h3": "npm:h3-nightly@latest"
}
}
```

If you are using a framework ([Nuxt](https://nuxt.com/) or [Nitro](https://nitro.unjs.io/)) that is using `h3`:

pnpm and yarn:

```json
{
"resolutions": {
"h3": "npm:h3-nightly@latest"
}
}
```

npm:

```json
{
"overrides": {
"h3": "npm:h3-nightly@latest"
}
}
```

**Note:** Make sure to recreate lockfile and `node_modules` after reinstall to avoid hoisting issues.

</details>

## Usage

```ts
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 <a href="https://github.com/unjs/listhen">listhen</a> for an elegant listener:

```ts
import { createApp, eventHandler, 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](./src/app.ts)) 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.

```ts
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](https://en.wikipedia.org/wiki/Radix_tree) and matched using [unjs/radix3](https://github.com/unjs/radix3).

For using nested routers, see [this example](./examples/nested-router.ts)

## More app usage examples

```js
// 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 });
```

## Utilities

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](https://www.jsdocs.io/package/h3#package-functions).

#### Body

- `readRawBody(event, encoding?)`
- `readBody(event)`
- `readValidatedBody(event, validate)`
- `readMultipartFormData(event)`

#### Request

- `getQuery(event)`
- `getValidatedQuery(event, validate)`
- `getRouterParams(event, { decode? })`
- `getRouterParam(event, name, { decode? })`
- `getValidatedRouterParams(event, validate, { decode? })`
- `getMethod(event, default?)`
- `isMethod(event, expected, allowHead?)`
- `assertMethod(event, expected, allowHead?)`
- `getRequestHeaders(event)` (alias: `getHeaders`)
- `getRequestHeader(event, name)` (alias: `getHeader`)
- `getRequestURL(event)`
- `getRequestHost(event)`
- `getRequestProtocol(event)`
- `getRequestPath(event)`
- `getRequestIP(event, { xForwardedFor: boolean })`

#### Response

- `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)`

#### Sanitize

- `sanitizeStatusMessage(statusMessage)`
- `sanitizeStatusCode(statusCode, default = 200)`

#### Error

- `sendError(event, error, debug?)`
- `createError({ statusCode, statusMessage, data? })`

#### Route

- `useBase(base, handler)`

#### Proxy

- `sendProxy(event, { target, ...options })`
- `proxyRequest(event, { target, ...options })`
- `fetchWithEvent(event, req, init, { fetch? }?)`
- `getProxyRequestHeaders(event)`

#### Cookie

- `parseCookies(event)`
- `getCookie(event, name)`
- `setCookie(event, name, value, opts?)`
- `deleteCookie(event, name, opts?)`
- `splitCookiesString(cookiesString)`

#### Session

- `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)`

#### Cache

- `handleCacheHeaders(event, opts)`

#### Cors

- `handleCors(options)` (see [h3-cors](https://github.com/NozomuIkuta/h3-cors) for more detail about options)
- `isPreflightRequest(event)`
- `isCorsOriginAllowed(event)`
- `appendCorsHeaders(event, options)` (see [h3-cors](https://github.com/NozomuIkuta/h3-cors) for more detail about options)
- `appendCorsPreflightHeaders(event, options)` (see [h3-cors](https://github.com/NozomuIkuta/h3-cors) for more detail about options)

## Community Packages

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.

- [h3-typebox](https://github.com/kevinmarrec/h3-typebox)
- `validateBody(event, schema)`
- `validateQuery(event, schema)`
- [h3-zod](https://github.com/wobsoriano/h3-zod)
- `useValidatedBody(event, schema)`
- `useValidatedQuery(event, schema)`
- [h3-valibot](https://github.com/intevel/h3-valibot)
- `useValidateBody(event, schema)`
- `useValidateParams(event, schema)`
- [h3-compression](https://github.com/CodeDredd/h3-compression)
- `useGZipCompression(event, response)`
- `useDeflateCompression(event, response)`
- `useBrotliCompression(event, response)`
- `useCompression(event, response)`
- `useGZipCompressionStream(event, response)`
- `useDeflateCompressionStream(event, response)`
- `useCompressionStream(event, response)`
- [@intlify/h3](https://github.com/intlify/h3)
- `defineI18nMiddleware(options)`
- `useTranslation(event)`
- `getHeaderLocale(event, options)`
- `getHeaderLocales(event, options)`
- `getCookieLocale(event, options)`
- `setCookieLocale(event, options)`
- `getPathLocale(event, options)`
- `getQueryLocale(event, options)`

## License

MIT
Expand Down
74 changes: 74 additions & 0 deletions docs/.config/docs.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# yaml-language-server: $schema=https://unpkg.com/undocs/schema/config.json
name: h3
shortDescription: The Web Framework for Modern JavaScript Era
description:
H(TTP) server framework built for high performance and portability running
in any JavaScript runtime.
github: unjs/h3
url: https://h3.unjs.io
automd: true
redirects: {}
landing:
heroLinks:
playOnline:
label: "Play Online"
icon: "i-simple-icons-lightning"
to: "https://stackblitz.com/github/unjs/h3/tree/main/playground"
contributors: true
featuresTitle: "The Web Framework for Modern JavaScript Era"
features:
# Runtime Agnostic
- title: "Runtime Agnostic"
description: "Your code will work on any JavaScript runtime including Node.js, Bun, Deno and Workers."
icon: "i-material-symbols-lock-open-right-outline-rounded"
to: ""
target: "_blank"

# Tree-shakable
- title: "Small and Tree-shakable"
description: "h3 core is super lightweight and tree-shakable, only what you use will be included in the the final bundle."
icon: "i-material-symbols-potted-plant-outline"
to: ""
target: "_blank"

# Composable
- title: "Composable"
description: "Expand your server and add capabilities. Your codebase will scale with your project."
icon: "i-fa-puzzle-piece"
to: ""
target: "_blank"

# Router
- title: "Fast Router"
description: "Super fast route matching using unjs/radix3"
icon: "i-fa-tree"
to: "https://github.com/unjs/radix3"
target: "_blank"

# Ecosystem
- title: "UnJS ecosystem"
description: "Built on top of powerful UnJS ecosystem powering Nitro, Nuxt and more frameworks!"
icon: "i-mdi-umbrella-outline"
to: "https://unjs.io"
target: "_blank"

# Made for Humans
- title: "Made for Humans"
description: "Elegant minimal API to implement HTTP handlers compatible with Web-Standards."
icon: "i-material-symbols-robot-2-sharp"
to: ""
target: "_blank"

# Compatibility
- title: "Compatible"
description: "Compatibility layer with node/connect/express middleware."
icon: "i-simple-icons-express"
to: ""
target: "_blank"

# Type Friendly
- title: "Type Friendly"
description: "Codebase fully written in TypeScript with strongly typed utils."
icon: "i-mdi-language-typescript"
to: ""
target: "_blank"
5 changes: 5 additions & 0 deletions docs/.docs/public/icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading