h3
Version:
58 lines (41 loc) • 1.98 kB
Markdown
# Nested Apps
> H3 has a native `mount` method for adding nested sub-apps to the main instance.
Typically, H3 projects consist of several [Event Handlers](/guide/basics/handler) defined in one or multiple files (or even [lazy loaded](/guide/basics/handler#lazy-handlers) for faster startup times).
It is sometimes more convenient to combine multiple `H3` instances or even use another HTTP framework used by a different team and mount it to the main app instance. H3 provides a native [`.mount`](/guide/api/h3#h3mount) method to facilitate this.
## Nested H3 Apps
H3 natively allows mounting sub-apps. When mounted, sub-app routes and middleware are **merged** with the base url prefix into the main app instance.
```js
import { H3, serve } from "h3";
const nestedApp = new H3()
.use((event) => {
event.res.headers.set("x-api", "1");
})
.get("/**:slug", (event) => ({
pathname: event.url.pathname,
slug: event.context.params?.slug,
}));
const app = new H3().mount("/api", nestedApp);
```
In the example above, when fetching the `/api/test` URL, `pathname` will be `/api/test` (the real path), and `slug` will be `/test` (wildcard param).
> [!NOTE]
> Global config and hooks won't be inherited from the nested app. Consider always setting them from the main app.
## Nested Web Standard Apps
Mount a `.fetch` compatible server instance like [Hono](https://hono.dev/) or [Elysia](https://elysiajs.com/) under the base URL.
> [!NOTE]
> Base prefix will be removed from `request.url` passed to the mounted app.
```js
import { H3 } from "h3";
import { Hono } from "hono";
import { Elysia } from "elysia";
const app = new H3()
.mount(
"/elysia",
new Elysia().get("/test", () => "Hello Elysia!"),
)
.mount(
"/hono",
new Hono().get("/test", (c) => c.text("Hello Hono!")),
);
```
> [!TIP]
> Similarly, you can mount an H3 app in [Hono](https://hono.dev/docs/api/hono#mount) or [Elysia](https://elysiajs.com/patterns/mount#mount-1).