0
# Next.js Special Files
1
2
File conventions for App Router and Pages Router.
3
4
## App Router Files
5
6
### layout.tsx
7
```typescript
8
export default function Layout({ children }) {
9
return (
10
<div>
11
<nav>Navigation</nav>
12
<main>{children}</main>
13
</div>
14
);
15
}
16
```
17
18
### page.tsx
19
```typescript
20
export default async function Page({ params, searchParams }) {
21
const data = await fetchData();
22
return <div>{data}</div>;
23
}
24
```
25
26
### loading.tsx
27
```typescript
28
export default function Loading() {
29
return <div>Loading...</div>;
30
}
31
```
32
33
### error.tsx
34
```typescript
35
'use client';
36
37
export default function Error({ error, reset }) {
38
return (
39
<div>
40
<h2>Error: {error.message}</h2>
41
<button onClick={reset}>Try again</button>
42
</div>
43
);
44
}
45
```
46
47
### not-found.tsx
48
```typescript
49
export default function NotFound() {
50
return (
51
<div>
52
<h2>Not Found</h2>
53
<Link href="/">Go Home</Link>
54
</div>
55
);
56
}
57
```
58
59
### route.ts
60
```typescript
61
import { NextRequest, NextResponse } from 'next/server';
62
63
export async function GET(request: NextRequest) {
64
return NextResponse.json({ data: 'value' });
65
}
66
```
67
68
### middleware.ts
69
```typescript
70
import { NextResponse } from 'next/server';
71
import type { NextRequest } from 'next/server';
72
73
export function middleware(request: NextRequest) {
74
if (request.nextUrl.pathname.startsWith('/dashboard')) {
75
return NextResponse.redirect(new URL('/login', request.url));
76
}
77
}
78
79
export const config = {
80
matcher: ['/dashboard/:path*'],
81
};
82
```
83
84
## Pages Router Files
85
86
### pages/_app.tsx
87
```typescript
88
export default function MyApp({ Component, pageProps }) {
89
return <Component {...pageProps} />;
90
}
91
```
92
93
### pages/_document.tsx
94
```typescript
95
import { Html, Head, Main, NextScript } from 'next/document';
96
97
export default function Document() {
98
return (
99
<Html>
100
<Head />
101
<body>
102
<Main />
103
<NextScript />
104
</body>
105
</Html>
106
);
107
}
108
```
109
110
### pages/404.tsx
111
```typescript
112
export default function Custom404() {
113
return <h1>404 - Page Not Found</h1>;
114
}
115
```
116