1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
|
Bun provides a fast API for resolving routes against file-system paths. This API is primarily intended for library authors. At the moment only Next.js-style file-system routing is supported, but other styles may be added in the future.
## Next.js-style
The `FileSystemRouter` class can resolve routes against a `pages` directory. (The Next.js 13 `app` directory is not yet supported.) Consider the following `pages` directory:
```txt
pages
├── index.tsx
├── settings.tsx
├── blog
│ ├── [slug].tsx
│ └── index.tsx
└── [[...catchall]].tsx
```
The `FileSystemRouter` can be used to resolve routes against this directory:
```ts
const router = new Bun.FileSystemRouter({
style: "nextjs",
dir: "./pages",
origin: "https://mydomain.com",
assetPrefix: "_next/static/"
});
router.match("/");
// =>
{
filePath: "/path/to/pages/index.tsx",
kind: "exact",
name: "/",
pathname: "/",
src: "https://mydomain.com/_next/static/pages/index.tsx"
}
```
Query parameters will be parsed and returned in the `query` property.
```ts
router.match("/settings?foo=bar");
// =>
{
filePath: "/Users/colinmcd94/Documents/bun/fun/pages/settings.tsx",
kind: "dynamic",
name: "/settings",
pathname: "/settings?foo=bar",
src: "https://mydomain.com/_next/static/pages/settings.tsx"
query: {
foo: "bar"
}
}
```
The router will automatically parse URL parameters and return them in the `params` property:
```ts
router.match("/blog/my-cool-post");
// =>
{
filePath: "/Users/colinmcd94/Documents/bun/fun/pages/blog/[slug].tsx",
kind: "dynamic",
name: "/blog/[slug]",
pathname: "/blog/my-cool-post",
src: "https://mydomain.com/_next/static/pages/blog/[slug].tsx"
params: {
slug: "my-cool-post"
}
}
```
The `.match()` method also accepts `Request` and `Response` objects. The `url` property will be used to resolve the route.
```ts
router.match(new Request("https://example.com/blog/my-cool-post"));
```
The router will read the directory contents on initialization. To re-scan the files, use the `.reload()` method.
```ts
router.reload();
```
## Reference
```ts
interface Bun {
class FileSystemRouter {
constructor(params: {
dir: string;
style: "nextjs";
origin?: string;
assetPrefix?: string;
});
reload(): void;
match(path: string | Request | Response): {
filePath: string;
kind: "exact" | "catch-all" | "optional-catch-all" | "dynamic";
name: string;
pathname: string;
src: string;
params?: Record<string, string>;
query?: Record<string, string>;
} | null
}
}
```
|