Next.js Code Review
Overview
Evaluates Next.js App Router code against best practices for Server Components, Client Components, Server Actions, caching strategies, and production-readiness criteria. Produces actionable findings categorized by severity with concrete code examples. Delegates to typescript-software-architect-review agent for architectural analysis.
When to Use
- Reviewing Next.js pages, layouts, and route segments before merging
- Validating Server Component vs Client Component boundaries
- Checking Server Actions for security and correctness
- Reviewing data fetching patterns (fetch, cache, revalidation)
- Evaluating caching strategies (static generation, ISR, dynamic rendering)
- Assessing middleware implementations (authentication, redirects, rewrites)
- Reviewing API route handlers for proper request/response handling
- Validating metadata configuration for SEO
- Checking loading, error, and not-found page implementations
- After implementing new Next.js features or migrating from Pages Router
Instructions
Identify Scope: Determine which Next.js route segments and components are under review. Use glob to discover page.tsx, layout.tsx, loading.tsx, error.tsx, route.ts, and middleware.ts files.
Analyze Component Boundaries: Verify proper Server Component / Client Component separation. Check that 'use client' is placed only where necessary and as deep in the component tree as possible. Ensure Server Components don't import client-only modules.
Review Data Fetching: Validate fetch patterns — check for proper cache and revalidate options, parallel data fetching with Promise.all, and avoidance of request waterfalls. Verify that server-side data fetching doesn't expose sensitive data to the client.
Evaluate Caching Strategy: Review static vs dynamic rendering decisions. Check generateStaticParams usage for static generation, revalidatePath/revalidateTag for on-demand revalidation, and proper cache headers for API routes.
Assess Server Actions: Review form actions for proper validation (both client and server-side), error handling, optimistic updates with useOptimistic, and security (ensure actions don't expose sensitive operations without authorization).
Check Middleware: Review middleware for proper request matching, authentication/authorization logic, response modification, and performance impact. Verify it runs only on necessary routes.
Review Metadata & SEO: Check generateMetadata functions, Open Graph tags, structured data, robots.txt, and sitemap.xml configurations. Verify dynamic metadata is properly implemented for pages with variable content.
Validate Findings: Before finalizing, verify each issue by checking the actual code context. Confirm the pattern violation exists, ensure the suggested fix is applicable to the codebase, and remove any false positives.
Produce Review Report: Generate a structured report with severity-classified findings (Critical, Warning, Suggestion), positive observations, and prioritized recommendations with code examples.
Examples
Example 1: Server/Client Component Boundaries
// ❌ Bad: Entire page marked as client when only a button needs interactivity
'use client';
export default async function ProductPage({ params }: { params: { id: string } }) {
const product = await fetch(`/api/products/${params.id}`);
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
<button => addToCart(product.id)}>Add to Cart</button>
</div>
);
}
// ✅ Good: Server Component with isolated Client Component
// app/products/[id]/page.tsx (Server Component)
import { AddToCartButton } from './add-to-cart-button';
export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const product = await getProduct(id);
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
<AddToCartButton productId={product.id} />
</div>
);
}
// app/products/[id]/add-to-cart-button.tsx (Client Component)
'use client';
export function AddToCartButton({ productId }: { productId: string }) {
return <button => addToCart(productId)}>Add to Cart</button>;
}
Example 2: Data Fetching Patterns
// ❌ Bad: Sequential data fetching creates waterfall
export default async function DashboardPage() {
const user = await getUser();
const orders = await getOrders(user.id);
const analytics = await getAnalytics(user.id);
return <Dashboard user={user} orders={orders} analytics={analytics} />;
}
// ✅ Good: Parallel data fetching with proper Suspense boundaries
export default async function DashboardPage() {
const user = await getUser();
const [orders, analytics] = await Promise.all([
getOrders(user.id),
getAnalytics(user.id),
]);
return <Dashboard user={user} orders={orders} analytics={analytics} />;
}
// ✅ Even better: Streaming with Suspense for independent sections
export default async function DashboardPage() {
const user = await getUser();
return (
<div>
<UserHeader user={user} />
<Suspense fallback={<OrdersSkeleton />}>
<OrdersSection userId={user.id} />
</Suspense>
<Suspense fallback={<AnalyticsSkeleton />}>
<AnalyticsSection userId={user.id} />
</Suspense>
</div>
);
}
Example 3: Server Actions Security
// ❌ Bad: Server Action without validation or authorization
'use server';
export async function deleteUser(id: string) {
await db.user.delete({ where: { id } });
}
// ✅ Good: Server Action with validation, authorization, and error handling
'use server';
import { z } from 'zod';
import { auth } from '@/lib/auth';
import { revalidatePath } from 'next/cache';
const deleteUserSchema = z.object({ id: z.string().uuid() });
export async function deleteUser(rawData: { id: string }) {
const session = await auth();
if (!session || session.user.role !== 'admin') {
throw new Error('Unauthorized');
}
const { id } = deleteUserSchema.parse(rawData);
await db.user.delete({ where: { id } });
revalidatePath('/admin/users');
}
Example 4: Caching and Revalidation
// ❌ Bad: No cache control, fetches on every request
export default async function BlogPage() {
const posts = await fetch('https://api.example.com/posts').then(r => r.json());
return <PostList posts={posts} />;
}
// ✅ Good: Explicit caching with time-based revalidation
export default async function BlogPage() {
const posts = await fetch('https://api.example.com/posts', {
next: { revalidate: 3600, tags: ['blog-posts'] },
}).then(r => r.json());
return <PostList posts={posts} />;
}
// Revalidation in Server Action
'use server';
export async function publishPost(data: FormData) {
await db.post.create({ data: parseFormData(data) });
revalidateTag('blog-posts');
}
Example 5: Middleware Review
// ❌ Bad: Middleware runs on all routes including static assets
import { NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
const session = request.cookies.get('session');
if (!session) {
return NextResponse.redirect(new URL('/login', request.url));
}
}
// Missing config.matcher
// ✅ Good: Scoped middleware with proper matcher
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const session = request.cookies.get('session');
if (!session) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*', '/api/protected/:path*'],
};
Review Output Format
Structure all code review findings as follows:
1. Summary
Brief overview with an overall quality score (1-10) and key observations.
2. Critical Issues (Must Fix)
Issues causing security vulnerabilities, data exposure, or broken functionality.
3. Warnings (Should Fix)
Issues that violate best practices, cause performance problems, or reduce maintainability.
4. Suggestions (Consider Improving)
Improvements for code organization, performance, or developer experience.
5. Positive Observations
Well-implemented patterns and good practices to acknowledge.
6. Recommendations
Prioritized next steps with code examples for the most impactful improvements.
Best Practices
- Keep
'use client' boundaries as deep in the tree as possible
- Fetch data in Server Components — avoid client-side fetching for initial data
- Use parallel data fetching (
Promise.all) to avoid request waterfalls
- Implement proper loading, error, and not-found states for every route segment
- Validate all Server Action inputs with Zod or similar libraries
- Use
revalidatePath/revalidateTag instead of time-based revalidation when possible
- Scope middleware to specific routes with
config.matcher
- Implement
generateMetadata for dynamic pages with variable content
- Use
generateStaticParams for static pages with known parameters
- Avoid importing server-only code in Client Components — use the
server-only package
Constraints and Warnings
- This skill targets Next.js App Router — Pages Router patterns may differ significantly
- Respect the project's Next.js version — some features are version-specific
- Do not suggest migrating from Pages Router to App Router unless explicitly requested
- Caching behavior differs between development and production — validate in production builds
- Server Actions must never expose sensitive operations without proper authentication checks
- Focus on high-confidence issues — avoid false positives on style preferences
References
See the references/ directory for detailed review checklists and pattern documentation:
references/app-router-patterns.md — App Router best practices and patterns
references/server-components.md — Server Component and Client Component boundary guide
references/performance.md — Next.js performance optimization checklist
1---2name: nextjs-code-review3description: Provides comprehensive code review capability for Next.js applications, validates Server Components, Client Components, Server Actions, caching strategies, metadata, API routes, middleware, and performance patterns. Use when reviewing Next.js App Router code changes, before merging pull requests, after implementing new features, or for architecture validation. Triggers on "review Next.js code", "Next.js code review", "check my Next.js app".4---5
6# Next.js Code Review
7
8## Overview
9
10Evaluates Next.js App Router code against best practices for Server Components, Client Components, Server Actions, caching strategies, and production-readiness criteria. Produces actionable findings categorized by severity with concrete code examples. Delegates to `typescript-software-architect-review` agent for architectural analysis.
11
12## When to Use
13
14- Reviewing Next.js pages, layouts, and route segments before merging
15- Validating Server Component vs Client Component boundaries
16- Checking Server Actions for security and correctness
17- Reviewing data fetching patterns (fetch, cache, revalidation)
18- Evaluating caching strategies (static generation, ISR, dynamic rendering)
19- Assessing middleware implementations (authentication, redirects, rewrites)
20- Reviewing API route handlers for proper request/response handling
21- Validating metadata configuration for SEO
22- Checking loading, error, and not-found page implementations
23- After implementing new Next.js features or migrating from Pages Router
24
25## Instructions
26
271. **Identify Scope**: Determine which Next.js route segments and components are under review. Use `glob` to discover `page.tsx`, `layout.tsx`, `loading.tsx`, `error.tsx`, `route.ts`, and `middleware.ts` files.
28
292. **Analyze Component Boundaries**: Verify proper Server Component / Client Component separation. Check that `'use client'` is placed only where necessary and as deep in the component tree as possible. Ensure Server Components don't import client-only modules.
30
313. **Review Data Fetching**: Validate fetch patterns — check for proper `cache` and `revalidate` options, parallel data fetching with `Promise.all`, and avoidance of request waterfalls. Verify that server-side data fetching doesn't expose sensitive data to the client.
32
334. **Evaluate Caching Strategy**: Review static vs dynamic rendering decisions. Check `generateStaticParams` usage for static generation, `revalidatePath`/`revalidateTag` for on-demand revalidation, and proper cache headers for API routes.
34
355. **Assess Server Actions**: Review form actions for proper validation (both client and server-side), error handling, optimistic updates with `useOptimistic`, and security (ensure actions don't expose sensitive operations without authorization).
36
376. **Check Middleware**: Review middleware for proper request matching, authentication/authorization logic, response modification, and performance impact. Verify it runs only on necessary routes.
38
397. **Review Metadata & SEO**: Check `generateMetadata` functions, Open Graph tags, structured data, `robots.txt`, and `sitemap.xml` configurations. Verify dynamic metadata is properly implemented for pages with variable content.
40
418. **Validate Findings**: Before finalizing, verify each issue by checking the actual code context. Confirm the pattern violation exists, ensure the suggested fix is applicable to the codebase, and remove any false positives.
42
439. **Produce Review Report**: Generate a structured report with severity-classified findings (Critical, Warning, Suggestion), positive observations, and prioritized recommendations with code examples.
44
45## Examples
46
47### Example 1: Server/Client Component Boundaries
48
49```tsx
50// ❌ Bad: Entire page marked as client when only a button needs interactivity
51'use client';
52
53export default async function ProductPage({ params }: { params: { id: string } }) {
54 const product = await fetch(`/api/products/${params.id}`);
55 return (
56 <div>
57 <h1>{product.name}</h1>
58 <p>{product.description}</p>
59 <button onClick={() => addToCart(product.id)}>Add to Cart</button>
60 </div>
61 );
62}
63
64// ✅ Good: Server Component with isolated Client Component
65// app/products/[id]/page.tsx (Server Component)
66import { AddToCartButton } from './add-to-cart-button';
67
68export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
69 const { id } = await params;
70 const product = await getProduct(id);
71
72 return (
73 <div>
74 <h1>{product.name}</h1>
75 <p>{product.description}</p>
76 <AddToCartButton productId={product.id} />
77 </div>
78 );
79}
80
81// app/products/[id]/add-to-cart-button.tsx (Client Component)
82'use client';
83
84export function AddToCartButton({ productId }: { productId: string }) {
85 return <button onClick={() => addToCart(productId)}>Add to Cart</button>;
86}
87```
88
89### Example 2: Data Fetching Patterns
90
91```tsx
92// ❌ Bad: Sequential data fetching creates waterfall
93export default async function DashboardPage() {
94 const user = await getUser();
95 const orders = await getOrders(user.id);
96 const analytics = await getAnalytics(user.id);
97 return <Dashboard user={user} orders={orders} analytics={analytics} />;
98}
99
100// ✅ Good: Parallel data fetching with proper Suspense boundaries
101export default async function DashboardPage() {
102 const user = await getUser();
103 const [orders, analytics] = await Promise.all([
104 getOrders(user.id),
105 getAnalytics(user.id),
106 ]);
107 return <Dashboard user={user} orders={orders} analytics={analytics} />;
108}
109
110// ✅ Even better: Streaming with Suspense for independent sections
111export default async function DashboardPage() {
112 const user = await getUser();
113 return (
114 <div>
115 <UserHeader user={user} />
116 <Suspense fallback={<OrdersSkeleton />}>
117 <OrdersSection userId={user.id} />
118 </Suspense>
119 <Suspense fallback={<AnalyticsSkeleton />}>
120 <AnalyticsSection userId={user.id} />
121 </Suspense>
122 </div>
123 );
124}
125```
126
127### Example 3: Server Actions Security
128
129```tsx
130// ❌ Bad: Server Action without validation or authorization
131'use server';
132
133export async function deleteUser(id: string) {
134 await db.user.delete({ where: { id } });
135}
136
137// ✅ Good: Server Action with validation, authorization, and error handling
138'use server';
139
140import { z } from 'zod';
141import { auth } from '@/lib/auth';
142import { revalidatePath } from 'next/cache';
143
144const deleteUserSchema = z.object({ id: z.string().uuid() });
145
146export async function deleteUser(rawData: { id: string }) {
147 const session = await auth();
148 if (!session || session.user.role !== 'admin') {
149 throw new Error('Unauthorized');
150 }
151
152 const { id } = deleteUserSchema.parse(rawData);
153 await db.user.delete({ where: { id } });
154 revalidatePath('/admin/users');
155}
156```
157
158### Example 4: Caching and Revalidation
159
160```tsx
161// ❌ Bad: No cache control, fetches on every request
162export default async function BlogPage() {
163 const posts = await fetch('https://api.example.com/posts').then(r => r.json());
164 return <PostList posts={posts} />;
165}
166
167// ✅ Good: Explicit caching with time-based revalidation
168export default async function BlogPage() {
169 const posts = await fetch('https://api.example.com/posts', {
170 next: { revalidate: 3600, tags: ['blog-posts'] },
171 }).then(r => r.json());
172 return <PostList posts={posts} />;
173}
174
175// Revalidation in Server Action
176'use server';
177export async function publishPost(data: FormData) {
178 await db.post.create({ data: parseFormData(data) });
179 revalidateTag('blog-posts');
180}
181```
182
183### Example 5: Middleware Review
184
185```typescript
186// ❌ Bad: Middleware runs on all routes including static assets
187import { NextResponse } from 'next/server';
188
189export function middleware(request: NextRequest) {
190 const session = request.cookies.get('session');
191 if (!session) {
192 return NextResponse.redirect(new URL('/login', request.url));
193 }
194}
195// Missing config.matcher
196
197// ✅ Good: Scoped middleware with proper matcher
198import { NextResponse } from 'next/server';
199import type { NextRequest } from 'next/server';
200
201export function middleware(request: NextRequest) {
202 const session = request.cookies.get('session');
203 if (!session) {
204 return NextResponse.redirect(new URL('/login', request.url));
205 }
206 return NextResponse.next();
207}
208
209export const config = {
210 matcher: ['/dashboard/:path*', '/api/protected/:path*'],
211};
212```
213
214## Review Output Format
215
216Structure all code review findings as follows:
217
218### 1. Summary
219Brief overview with an overall quality score (1-10) and key observations.
220
221### 2. Critical Issues (Must Fix)
222Issues causing security vulnerabilities, data exposure, or broken functionality.
223
224### 3. Warnings (Should Fix)
225Issues that violate best practices, cause performance problems, or reduce maintainability.
226
227### 4. Suggestions (Consider Improving)
228Improvements for code organization, performance, or developer experience.
229
230### 5. Positive Observations
231Well-implemented patterns and good practices to acknowledge.
232
233### 6. Recommendations
234Prioritized next steps with code examples for the most impactful improvements.
235
236## Best Practices
237
238- Keep `'use client'` boundaries as deep in the tree as possible
239- Fetch data in Server Components — avoid client-side fetching for initial data
240- Use parallel data fetching (`Promise.all`) to avoid request waterfalls
241- Implement proper loading, error, and not-found states for every route segment
242- Validate all Server Action inputs with Zod or similar libraries
243- Use `revalidatePath`/`revalidateTag` instead of time-based revalidation when possible
244- Scope middleware to specific routes with `config.matcher`
245- Implement `generateMetadata` for dynamic pages with variable content
246- Use `generateStaticParams` for static pages with known parameters
247- Avoid importing server-only code in Client Components — use the `server-only` package
248
249## Constraints and Warnings
250
251- This skill targets Next.js App Router — Pages Router patterns may differ significantly
252- Respect the project's Next.js version — some features are version-specific
253- Do not suggest migrating from Pages Router to App Router unless explicitly requested
254- Caching behavior differs between development and production — validate in production builds
255- Server Actions must never expose sensitive operations without proper authentication checks
256- Focus on high-confidence issues — avoid false positives on style preferences
257
258## References
259
260See the `references/` directory for detailed review checklists and pattern documentation:
261- `references/app-router-patterns.md` — App Router best practices and patterns
262- `references/server-components.md` — Server Component and Client Component boundary guide
263- `references/performance.md` — Next.js performance optimization checklist