---
# System prepended metadata

title: Defining routes
tags: [brew-js]

---

---
tags: brew-js
---

# Defining routes

A set of routes define what path the app can land to. The routes are matched in order and the first matched route will be used to determine the route parameters.

```typescript
app.useRouter({
    routes: [
        '/user/{id}'
        '/user',
        '/'
    ]
})
```

## Route parameter


Route parameters can be used to capture a specific segment and be populated to the `app.route` dictionary. They can also be used to define dynamic routes.

For example, the route `/user/{id}` will match:

| Path      | `app.route.id` |
| --------- | -------------- |
| `/user/1` | `1`            |


### Optional

An optional route parameter can be specified by `?` after parameter name, for example the following route will match `/user` and `/user/xxx`.

```
/user/{id?}
```

All following parameters are also considered optional after an explicitly optional parameter. For example, `action` is also optional in the following route:

```
/user/{id?}/{action}
```

### Regex

To match a segment with a certain pattern, regular expression can be specified after parameter name separated by a colon `:`.

```
/user/{id:\d+}
```

:::info
In JavaScript string literal the backslash character need to be escaped as:
`"/user/{id:\\d+}"`
:::

The expression always match the whole segment, therefore `^` and `$` is omitted.

### Wildcard (remaining segment)

The route is a match as long as the parts before `*` is matched. For example the following route will match `/user/1`, `/user/1/xxx`, `/user/1/xxx/yyy` and so on:

```
/user/{id}/*
```

And the `*` part will be populated to `app.route.remainingSegments`.


| Path              | `app.route.id` | `app.route.remainingSegments` |
| ----------------- | -------------- | ----------------------------- |
| `/user/1`         | `1`            | `/`                           |
| `/user/1/xxx`     | `1`            | `/xxx`                        |
| `/user/1/xxx/yyy` | `1`            | `/xxx/yyy`                    |


## Catch-all route

A catch-all route `/*` will match any paths. Add this at the end if a "page not found" screen is desired.
