Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
8 changes: 4 additions & 4 deletions docs/1.guide/1.index.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Create a new file `app.ts` (or `app.js`):

```ts [app.ts]
// Import h3 as npm dependency
import { createApp, createRouter, eventHandler } from "h3";
import { createApp, createRouter, defineEventHandler } from "h3";

// Create an app instance
export const app = createApp();
Expand All @@ -33,7 +33,7 @@ app.use(router);
// Add a new route that matches GET requests to / path
router.get(
"/",
eventHandler((event) => {
defineEventHandler((event) => {
return { message: "⚑️ Tadaa!" };
}),
);
Expand Down Expand Up @@ -71,7 +71,7 @@ app.use(router);
Now it it time to add our first endpoint. In h3, request handlers can be defined using `defineEventHandler` or `eventHandler` helpers (they are aliases). Using wrappers, h3 can supercharge your code with better typehints and future compatibility.

```ts
eventHandler((event) => {});
defineEventHandler((event) => {});
```

What is beatiful in h3 is that all you have to do to make a reponse, is to simply return it! Responses can be simple string, JSON objects, data buffers, streams or standard [Web Response](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).
Expand Down Expand Up @@ -99,7 +99,7 @@ You can use this method for Node.js and Bun.
You can directly import h3 from CDN. This method can be used for Bun, Deno and other runtimes such as Cloudflare Workers (you need an adapter).

```js
import { createApp, eventHandler, toWebhandler } from "https://esm.sh/h3";
import { createApp, toWebhandler } from "https://esm.sh/h3";

export const app = createApp();

Expand Down
10 changes: 6 additions & 4 deletions docs/1.guide/2.app.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ const app = createApp({
You can register [event handlers](/guide/event-handler) to app instance using the `app.use`:

```js
import { defineEventHandler } from "h3";

app.use(
"/hello",
defineEventHandler((event) => {
Expand All @@ -72,13 +74,13 @@ You can define multiple event handlers for the same route. h3 will try to to cal
```js
app.use(
"/",
eventHandler((event) => {
defineEventHandler((event) => {
return "First";
}),
);
app.use(
"/",
eventHandler((event) => {
defineEventHandler((event) => {
return "Second";
}),
);
Expand All @@ -91,14 +93,14 @@ However, if you do not return a response from the first event handler, the secon
```js
app.use(
"/",
eventHandler((event) => {
defineEventHandler((event) => {
console.log("First");
// No response returned
}),
);
app.use(
"/",
eventHandler((event) => {
defineEventHandler((event) => {
return "Second";
}),
);
Expand Down
70 changes: 28 additions & 42 deletions docs/1.guide/2.event-handler.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ An event handler is a function that receive an `Event` instance and returns a re
You can define event handlers using `defineEventHandler` or [`eventHandler` utilities:

> [!NOTE]
> You can use `eventHandler` and `defineEventHandler` interchangeably. They are aliases. You can use the one you prefer but **stick to it** for consistency.
> You can use `defineEventHandler` and `eventHandler` interchangeably. They are aliases. You can use the one you prefer but **stick to it** for consistency.

```js
import { defineEventHandler } from "h3";
Expand All @@ -28,8 +28,6 @@ defineEventHandler((event) => {
The callback function can be sync or async:

```js
import { defineEventHandler } from "h3";

defineEventHandler(async (event) => {
return "Response";
});
Expand Down Expand Up @@ -66,38 +64,36 @@ Any of above values could also be wrapped in a [`Promise`](https://developer.moz
**Example:** Send HTML response:

```js
app.use(eventHandler(async (event) => "<h1>Hello world!</h1>"));
app.use(defineEventHandler(async (event) => "<h1>Hello world!</h1>"));
```

**Example:** Send JSON response:

```js
app.use(
"/api",
eventHandler(async (event) => ({ url: event.node.req.url })),
defineEventHandler(async (event) => ({ url: event.node.req.url })),
);
```

**Example:** Send a promise:

```js
app.use(
defineEventHandlers(async (event) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ url: event.node.req.url });
}, 1000);
});
}),
);
app.use(defineEventHandlers(async (event) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ url: event.node.req.url });
}, 1000);
});
}));
Comment thread
pi0 marked this conversation as resolved.
Outdated
```

## Error Handling

You can easily control the error returned by using the `createError` utility.

```js
import { createError } from "h3";
import { createError, defineEventHandler } from "h3";

app.use(
"/hello",
Expand Down Expand Up @@ -142,16 +138,14 @@ A lazy event handler must return an event handler:
```js
import { defineLazyEventHandler } from "h3";

app.use(
defineLazyEventHandler(() => {
console.log("This will be executed only once");
// This will be executed only once
return defineEventHandler((event) => {
// This will be executed on every request
return "Response";
});
}),
);
app.use(defineLazyEventHandler(() => {
console.log("This will be executed only once");
// This will be executed only once
return defineEventHandler((event) => {
// This will be executed on every request
return "Response";
});
}));
```

This is useful to define some one-time logic such as configuration, class initialization, heavy computation, etc.
Expand All @@ -167,8 +161,6 @@ Event handlers that don't return any value act as middleware. They can be used t
Similar to normal event handlers, you can define middleware using `defineEventHandler` or `eventHandler` utilities:

```js
import { defineEventHandler } from "h3";

defineEventHandler((event) => {
console.log(`Middleware. Path: ${event.path}`);
});
Expand All @@ -183,21 +175,15 @@ defineEventHandler((event) => {
Then, you can register middleware to [app instance](/guide/app) using the `use` method:

```js
app.use(
defineEventHandler((event) => {
console.log("Middleware 1");
}),
);
app.use(
defineEventHandler((event) => {
console.log("Middleware 2");
}),
);
app.use(
defineEventHandler((event) => {
return "Response";
}),
);
app.use(defineEventHandler((event) => {
console.log("Middleware 1");
}));
app.use(defineEventHandler((event) => {
console.log("Middleware 2");
}));
app.use(defineEventHandler((event) => {
return "Response";
}));
```

You can define as much middleware as you need. They will be called in order of registration.
Expand Down
54 changes: 24 additions & 30 deletions docs/1.guide/4.event.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,28 +13,26 @@ An event is passed through all the lifecycle hooks and composable utils to use i
**Example:**

```js
import { defineEventHandler, readBody, query } from "h3";

app.use(
defineEventHandler((event) => {
// Log event. `.toString()` stringifies to a simple string like `[GET] /<path>`
console.log(`Request: ${event.toString()}`);

// Parse query parms
const query = getQuery(event)

// Try to read request body
const body = await readBody(event).catch(() => {})

// Echo back request as response
return {
path: event.path,
method: event.method,
query,
body,
}
}),
);
import { defineEventHandler, getQuery, readBody } from "h3";
Comment thread
pi0 marked this conversation as resolved.

app.use(defineEventHandler((event) => {
// Log event. `.toString()` stringifies to a simple string like `[GET] /<path>`
console.log(`Request: ${event.toString()}`);

// Parse query parms
const query = getQuery(event)

// Try to read request body
const body = await readBody(event).catch(() => {})

// Echo back request as response
return {
path: event.path,
method: event.method,
query,
body,
}
}));
```

## Properties
Expand Down Expand Up @@ -108,15 +106,11 @@ You must craft a response using the [`Response`](https://developer.mozilla.org/e
**Example:**

```js
import { defineEventHandler } from "h3";

app.use(
defineEventHandler((event) => {
await event.respondWith(new Response("Hello World"));
defineEventHandler((event) => {
await event.respondWith(new Response("Hello World"));

return "..."; // DOES NOT WORKS
}),
);
return "..."; // DOES NOT WORKS
});
Comment thread
pi0 marked this conversation as resolved.
```

With this example, the client will receive `Hello World`.
4 changes: 2 additions & 2 deletions docs/1.guide/5.router.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Using h3 router allows more advanced and convenient routing system such as param
First, you need to create a router using `createRouter` utility and add it to app stack.

```js
import { createApp, defineEventHandler, createRouter } from "h3";
import { createApp, createRouter, defineEventHandler } from "h3";

const app = createApp();
const router = createRouter();
Expand Down Expand Up @@ -115,7 +115,7 @@ This will match `/hello`, `/hello/world`, `/hello/123`, `/hello/world/123`, etc.
You can nest routers to create a tree of routers. This is useful to split your application into multiple parts like the API and the website.

```js
import { createRouter, createApp } from "h3";
import { createApp, createRouter, defineEventHandler, useBase } from "h3";

export const app = createApp();

Expand Down
4 changes: 2 additions & 2 deletions docs/3.adapters/2.web.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ In order to run h3 apps in web compatible edge runtimes supporting [`fetch` API]
First, create app entry:

```js [app.mjs]
import { createApp, eventHandler } from "h3";
import { createApp, defineEventHandler } from "h3";

export const app = createApp();

app.use(eventHandler(() => "Hello world!"));
app.use(defineEventHandler(() => "Hello world!"));
```

Create web entry:
Expand Down
4 changes: 2 additions & 2 deletions docs/3.adapters/3.plain.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ There might be cases where your runtime is nither Node.js or Web compatible. Usi
First, create app entry:

```js [app.mjs]
import { createApp, eventHandler } from "h3";
import { createApp, defineEventHandler } from "h3";

export const app = createApp();

app.use(eventHandler(() => "Hello world!"));
app.use(defineEventHandler(() => "Hello world!"));
```

Create plain entry:
Expand Down
4 changes: 2 additions & 2 deletions docs/3.adapters/netlify.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ You can directly host your h3 applications to [Netlify Edge](https://www.netlify
Create app entry:

```js [app.mjs]
import { createApp, eventHandler } from "h3";
import { createApp, defineEventHandler } from "h3";

export const app = createApp();

app.use(eventHandler(() => "Hello world!"));
app.use(defineEventHandler(() => "Hello world!"));
```

Create entry for netlify-edge:
Expand Down
2 changes: 1 addition & 1 deletion docs/4.examples/from-expressjs-to-h3.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ Let's see how to do the same thing with h3:
/**
* h3 example app.
*/
import { defineEventHandler, createApp } from "h3";
import { createApp, defineEventHandler } from "h3";

export const app = createApp();

Expand Down
30 changes: 10 additions & 20 deletions docs/4.examples/handle-cookie.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,9 @@ To set a cookie, you need to use `setCookie` in an event handler:
```ts
import { defineEventHandler, setCookie } from "h3";

app.use(
defineEventHandler(async (event) => {
setCookie(event, "name", "value", { maxAge: 60 * 60 * 24 * 7 });

return;
}),
);
app.use(defineEventHandler(async (event) => {
setCookie(event, "name", "value", { maxAge: 60 * 60 * 24 * 7 });
}));
```

In the options, you can configure the [cookie flags](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie):
Expand All @@ -43,13 +39,11 @@ To get a cookie, you need to use `getCookie` in an event handler.
```ts
import { defineEventHandler, getCookie } from "h3";

app.use(
defineEventHandler(async (event) => {
const name = getCookie(event, "name");
app.use(defineEventHandler(async (event) => {
const name = getCookie(event, "name");

return;
}),
);
// do something...
}));
```

This will return the value of the cookie if it exists, or `undefined` otherwise.
Expand All @@ -61,13 +55,9 @@ To delete a cookie, you need to use `deleteCookie` in an event handler:
```ts
import { defineEventHandler, deleteCookie } from "h3";

app.use(
defineEventHandler(async (event) => {
deleteCookie(event, "name");

return;
}),
);
app.use(defineEventHandler(async (event) => {
deleteCookie(event, "name");
}));
```

The utility `deleteCookie` is a wrapper around `setCookie` with the value set to `""` and the `maxAge` set to `0`.
Expand Down
Loading