0
# Next.js API Reference
1
2
Complete API documentation for Next.js App Router.
3
4
## Navigation
5
6
### Client Hooks
7
8
**useRouter**
9
```typescript
10
import { useRouter } from 'next/navigation';
11
12
const router = useRouter();
13
router.push('/about'); // Navigate
14
router.replace('/login'); // Replace history
15
router.refresh(); // Refresh data
16
router.back(); // Go back
17
```
18
19
**usePathname**
20
```typescript
21
import { usePathname } from 'next/navigation';
22
23
const pathname = usePathname(); // '/about'
24
```
25
26
**useSearchParams**
27
```typescript
28
import { useSearchParams } from 'next/navigation';
29
30
const params = useSearchParams();
31
const q = params.get('q');
32
```
33
34
**useParams**
35
```typescript
36
import { useParams } from 'next/navigation';
37
38
const params = useParams<{ slug: string }>();
39
```
40
41
### Server Functions
42
43
**redirect**
44
```typescript
45
import { redirect } from 'next/navigation';
46
47
export default async function Page() {
48
const user = await getUser();
49
if (!user) redirect('/login');
50
return <div>{user.name}</div>;
51
}
52
```
53
54
**notFound**
55
```typescript
56
import { notFound } from 'next/navigation';
57
58
export default async function Post({ params }) {
59
const post = await getPost(params.id);
60
if (!post) notFound();
61
return <article>{post.content}</article>;
62
}
63
```
64
65
**forbidden & unauthorized**
66
```typescript
67
import { forbidden, unauthorized } from 'next/navigation';
68
69
if (!user) unauthorized();
70
if (!user.isAdmin) forbidden();
71
```
72
73
## Components
74
75
### Link
76
77
```typescript
78
import Link from 'next/link';
79
80
<Link href="/about">About</Link>
81
<Link href="/dashboard" scroll={false}>Dashboard</Link>
82
<Link href="/heavy" prefetch={false}>Heavy Page</Link>
83
```
84
85
### Image
86
87
```typescript
88
import Image from 'next/image';
89
90
<Image
91
src="/photo.jpg"
92
alt="Photo"
93
width={800}
94
height={600}
95
priority // Above-the-fold
96
placeholder="blur"
97
quality={85}
98
/>
99
```
100
101
### Script
102
103
```typescript
104
import Script from 'next/script';
105
106
<Script
107
src="https://example.com/script.js"
108
strategy="afterInteractive"
109
onReady={() => console.log('Ready')}
110
/>
111
```
112
113
### Form
114
115
```typescript
116
import Form from 'next/form';
117
118
<Form action={async (formData) => {
119
'use server';
120
await processForm(formData);
121
redirect('/success');
122
}}>
123
<input name="title" />
124
<button type="submit">Submit</button>
125
</Form>
126
```
127
128
## Server Utilities
129
130
### NextRequest & NextResponse
131
132
```typescript
133
import { NextRequest, NextResponse } from 'next/server';
134
135
export async function GET(request: NextRequest) {
136
const searchParams = request.nextUrl.searchParams;
137
const q = searchParams.get('q');
138
139
return NextResponse.json({ data: 'value', query: q });
140
}
141
142
export async function POST(request: NextRequest) {
143
const body = await request.json();
144
return NextResponse.json(body, { status: 201 });
145
}
146
```
147
148
### Headers & Cookies
149
150
```typescript
151
import { headers, cookies } from 'next/headers';
152
153
export default async function Page() {
154
const headersList = await headers();
155
const userAgent = headersList.get('user-agent');
156
157
const cookieStore = await cookies();
158
const token = cookieStore.get('token');
159
160
return <div>{userAgent}</div>;
161
}
162
```
163
164
## Caching & Revalidation
165
166
### Fetch Options
167
168
```typescript
169
// Time-based revalidation (ISR)
170
const res = await fetch('https://api.example.com/data', {
171
next: { revalidate: 3600 }
172
});
173
174
// Tag-based revalidation
175
const posts = await fetch('https://api.example.com/posts', {
176
next: { tags: ['posts'] }
177
});
178
179
// Force no cache
180
const res = await fetch('https://api.example.com/data', {
181
cache: 'no-store'
182
});
183
```
184
185
### Revalidation Functions
186
187
```typescript
188
import { revalidatePath, revalidateTag } from 'next/cache';
189
190
// Revalidate by path
191
revalidatePath('/posts');
192
193
// Revalidate by tag
194
revalidateTag('posts');
195
```
196
197
### Cache Control
198
199
```typescript
200
import { unstable_cache, unstable_noStore } from 'next/cache';
201
202
// Cache expensive operation
203
const getCachedData = unstable_cache(
204
async () => await db.query(),
205
['users'],
206
{ revalidate: 3600, tags: ['users'] }
207
);
208
209
// Force dynamic
210
export default async function Page() {
211
unstable_noStore();
212
const data = await fetchData();
213
return <div>{data}</div>;
214
}
215
```
216
217
## Route Segment Config
218
219
```typescript
220
// Rendering behavior
221
export const dynamic = 'force-dynamic'; // or 'force-static', 'auto'
222
223
// Revalidation
224
export const revalidate = 60; // seconds
225
226
// Runtime
227
export const runtime = 'nodejs' | 'edge';
228
229
// Duration limit
230
export const maxDuration = 60; // seconds
231
```
232
233
## Configuration
234
235
### next.config.js
236
237
```typescript
238
import type { NextConfig } from 'next';
239
240
const config: NextConfig = {
241
reactStrictMode: true,
242
images: {
243
domains: ['example.com'],
244
},
245
redirects: async () => [
246
{ source: '/old', destination: '/new', permanent: true },
247
],
248
};
249
250
export default config;
251
```
252
253
### Metadata
254
255
```typescript
256
import type { Metadata } from 'next';
257
258
export const metadata: Metadata = {
259
title: 'Page Title',
260
description: 'Description',
261
openGraph: {
262
title: 'OG Title',
263
images: ['/og-image.jpg'],
264
},
265
};
266
```
267
268
## Font Optimization
269
270
### Google Fonts
271
272
```typescript
273
import { Inter } from 'next/font/google';
274
275
const inter = Inter({
276
subsets: ['latin'],
277
variable: '--font-inter',
278
});
279
280
export default function Layout({ children }) {
281
return <html className={inter.variable}>{children}</html>;
282
}
283
```
284
285
### Local Fonts
286
287
```typescript
288
import localFont from 'next/font/local';
289
290
const myFont = localFont({
291
src: './fonts/my-font.woff2',
292
variable: '--font-custom',
293
display: 'swap',
294
});
295
```
296
297
## CLI Commands
298
299
```bash
300
# Development
301
next dev # Start dev server
302
next dev --turbo # With Turbopack
303
304
# Production
305
next build # Build for production
306
next start # Start production server
307
308
# Other
309
next lint # Run linter
310
next info # System info
311
```
312
313
## Complete Type Interfaces
314
315
### Link Props
316
```typescript
317
interface LinkProps {
318
href: string | UrlObject;
319
replace?: boolean;
320
scroll?: boolean;
321
prefetch?: boolean | null;
322
locale?: string | false;
323
}
324
```
325
326
### Image Props
327
```typescript
328
interface ImageProps {
329
src: string | StaticImageData;
330
alt: string;
331
width?: number;
332
height?: number;
333
fill?: boolean;
334
sizes?: string;
335
quality?: number;
336
priority?: boolean;
337
placeholder?: 'blur' | 'empty';
338
blurDataURL?: string;
339
}
340
```
341
342
### Script Props
343
```typescript
344
interface ScriptProps {
345
src?: string;
346
strategy?: 'beforeInteractive' | 'afterInteractive' | 'lazyOnload' | 'worker';
347
onLoad?: () => void;
348
onReady?: () => void;
349
onError?: (e: any) => void;
350
id?: string;
351
}
352
```
353
354
### Navigation Options
355
```typescript
356
interface NavigateOptions {
357
scroll?: boolean;
358
}
359
360
interface PrefetchOptions {
361
kind?: 'auto' | 'full' | 'temporary';
362
}
363
```
364
365