h3
Version:
93 lines (60 loc) • 2.39 kB
Markdown
# Routing
> Each request is matched to one (most specific) route handler.
## Adding Routes
You can register route [handlers](/guide/basics/handler) to [H3 instance](/guide/api/h3) using [`H3.on`](/guide/api/h3#h3on), [`H3.[method]`](/guide/api/h3#h3method), or [`H3.all`](/guide/api/h3#h3all).
> [!TIP]
> Router is powered by [🌳 Rou3](https://github.com/h3js/rou3), an ultra-fast and tiny route matcher engine.
**Example:** Register a route to match requests to the `/hello` endpoint with HTTP **GET** method.
- Using [`H3.[method]`](/guide/api/h3#h3method)
```js
app.get("/hello", () => "Hello world!");
```
- Using [`H3.on`](/guide/api/h3#h3on)
```js
app.on("GET", "/hello", () => "Hello world!");
```
You can register multiple event handlers for the same route with different methods:
```js
app
.get("/hello", () => "GET Hello world!")
.post("/hello", () => "POST Hello world!")
.all("/hello", () => "Any other method!");
```
You can also use [`H3.all`](/guide/api/h3#h3all) method to register a route accepting any HTTP method:
```js
app.all("/hello", (event) => `This is a ${event.req.method} request!`);
```
## Dynamic Routes
You can define dynamic route parameters using `:` prefix:
```js
// [GET] /hello/Bob => "Hello, Bob!"
app.get("/hello/:name", (event) => {
return `Hello, ${event.context.params.name}!`;
});
```
Instead of named parameters, you can use `*` for unnamed **optional** parameters:
```js
app.get("/hello/*", (event) => `Hello!`);
```
## Wildcard Routes
Adding `/hello/:name` route will match `/hello/world` or `/hello/123`. But it will not match `/hello/foo/bar`.
When you need to match multiple levels of sub routes, you can use `**` prefix:
```js
app.get("/hello/**", (event) => `Hello ${event.context.params._}!`);
```
This will match `/hello`, `/hello/world`, `/hello/123`, `/hello/world/123`, etc.
> [!NOTE]
> Param `_` will store the full wildcard content as a single string.
## Route Meta
You can define optional route meta when registering them, accessible from any middleware.
```js
import { H3 } from "h3";
const app = new H3();
app.use((event) => {
console.log(event.context.matchedRoute?.meta); // { auth: true }
});
app.get("/", (event) => "Hi!", { meta: { auth: true } });
```
<read-more>
It is also possible to add route meta when defining them using `defineHandler` object syntax.
</read-more>