Next.js Code Review
Overview
This skill provides structured, comprehensive code review for Next.js applications built with the App Router. It evaluates code against Next.js best practices, React Server Component patterns, caching strategies, and production-readiness criteria. The review produces actionable findings categorized by severity (Critical, Warning, Suggestion) with concrete code examples for improvements.
This skill delegates to the typescript-software-architect-review agent for deep architectural analysis when invoked through the agent system.
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.
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".4allowed-tools: Read, Edit, Grep, Glob, Bash5metadata:6 source: https://skillmd.com/skills/levalencia/nextjs-code-review7---89# Next.js Code Review1011## Overview1213This skill provides structured, comprehensive code review for Next.js applications built with the App Router. It evaluates code against Next.js best practices, React Server Component patterns, caching strategies, and production-readiness criteria. The review produces actionable findings categorized by severity (Critical, Warning, Suggestion) with concrete code examples for improvements.1415This skill delegates to the `typescript-software-architect-review` agent for deep architectural analysis when invoked through the agent system.1617## When to Use1819- Reviewing Next.js pages, layouts, and route segments before merging20- Validating Server Component vs Client Component boundaries21- Checking Server Actions for security and correctness22- Reviewing data fetching patterns (fetch, cache, revalidation)23- Evaluating caching strategies (static generation, ISR, dynamic rendering)24- Assessing middleware implementations (authentication, redirects, rewrites)25- Reviewing API route handlers for proper request/response handling26- Validating metadata configuration for SEO27- Checking loading, error, and not-found page implementations28- After implementing new Next.js features or migrating from Pages Router2930## Instructions31321. **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.33342. **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.35363. **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.37384. **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.39405. **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).41426. **Check Middleware**: Review middleware for proper request matching, authentication/authorization logic, response modification, and performance impact. Verify it runs only on necessary routes.43447. **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.45468. **Produce Review Report**: Generate a structured report with severity-classified findings (Critical, Warning, Suggestion), positive observations, and prioritized recommendations with code examples.4748## Examples4950### Example 1: Server/Client Component Boundaries5152```tsx53// ❌ Bad: Entire page marked as client when only a button needs interactivity54'use client';5556export default async function ProductPage({ params }: { params: { id: string } }) {57 const product = await fetch(`/api/products/${params.id}`);58 return (59 <div>60 <h1>{product.name}</h1>61 <p>{product.description}</p>62 <button onClick={() => addToCart(product.id)}>Add to Cart</button>63 </div>64 );65}6667// ✅ Good: Server Component with isolated Client Component68// app/products/[id]/page.tsx (Server Component)69import { AddToCartButton } from './add-to-cart-button';7071export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {72 const { id } = await params;73 const product = await getProduct(id);7475 return (76 <div>77 <h1>{product.name}</h1>78 <p>{product.description}</p>79 <AddToCartButton productId={product.id} />80 </div>81 );82}8384// app/products/[id]/add-to-cart-button.tsx (Client Component)85'use client';8687export function AddToCartButton({ productId }: { productId: string }) {88 return <button onClick={() => addToCart(productId)}>Add to Cart</button>;89}90```9192### Example 2: Data Fetching Patterns9394```tsx95// ❌ Bad: Sequential data fetching creates waterfall96export default async function DashboardPage() {97 const user = await getUser();98 const orders = await getOrders(user.id);99 const analytics = await getAnalytics(user.id);100 return <Dashboard user={user} orders={orders} analytics={analytics} />;101}102103// ✅ Good: Parallel data fetching with proper Suspense boundaries104export default async function DashboardPage() {105 const user = await getUser();106 const [orders, analytics] = await Promise.all([107 getOrders(user.id),108 getAnalytics(user.id),109 ]);110 return <Dashboard user={user} orders={orders} analytics={analytics} />;111}112113// ✅ Even better: Streaming with Suspense for independent sections114export default async function DashboardPage() {115 const user = await getUser();116 return (117 <div>118 <UserHeader user={user} />119 <Suspense fallback={<OrdersSkeleton />}>120 <OrdersSection userId={user.id} />121 </Suspense>122 <Suspense fallback={<AnalyticsSkeleton />}>123 <AnalyticsSection userId={user.id} />124 </Suspense>125 </div>126 );127}128```129130### Example 3: Server Actions Security131132```tsx133// ❌ Bad: Server Action without validation or authorization134'use server';135136export async function deleteUser(id: string) {137 await db.user.delete({ where: { id } });138}139140// ✅ Good: Server Action with validation, authorization, and error handling141'use server';142143import { z } from 'zod';144import { auth } from '@/lib/auth';145import { revalidatePath } from 'next/cache';146147const deleteUserSchema = z.object({ id: z.string().uuid() });148149export async function deleteUser(rawData: { id: string }) {150 const session = await auth();151 if (!session || session.user.role !== 'admin') {152 throw new Error('Unauthorized');153 }154155 const { id } = deleteUserSchema.parse(rawData);156 await db.user.delete({ where: { id } });157 revalidatePath('/admin/users');158}159```160161### Example 4: Caching and Revalidation162163```tsx164// ❌ Bad: No cache control, fetches on every request165export default async function BlogPage() {166 const posts = await fetch('https://api.example.com/posts').then(r => r.json());167 return <PostList posts={posts} />;168}169170// ✅ Good: Explicit caching with time-based revalidation171export default async function BlogPage() {172 const posts = await fetch('https://api.example.com/posts', {173 next: { revalidate: 3600, tags: ['blog-posts'] },174 }).then(r => r.json());175 return <PostList posts={posts} />;176}177178// Revalidation in Server Action179'use server';180export async function publishPost(data: FormData) {181 await db.post.create({ data: parseFormData(data) });182 revalidateTag('blog-posts');183}184```185186### Example 5: Middleware Review187188```typescript189// ❌ Bad: Middleware runs on all routes including static assets190import { NextResponse } from 'next/server';191192export function middleware(request: NextRequest) {193 const session = request.cookies.get('session');194 if (!session) {195 return NextResponse.redirect(new URL('/login', request.url));196 }197}198// Missing config.matcher199200// ✅ Good: Scoped middleware with proper matcher201import { NextResponse } from 'next/server';202import type { NextRequest } from 'next/server';203204export function middleware(request: NextRequest) {205 const session = request.cookies.get('session');206 if (!session) {207 return NextResponse.redirect(new URL('/login', request.url));208 }209 return NextResponse.next();210}211212export const config = {213 matcher: ['/dashboard/:path*', '/api/protected/:path*'],214};215```216217## Review Output Format218219Structure all code review findings as follows:220221### 1. Summary222Brief overview with an overall quality score (1-10) and key observations.223224### 2. Critical Issues (Must Fix)225Issues causing security vulnerabilities, data exposure, or broken functionality.226227### 3. Warnings (Should Fix)228Issues that violate best practices, cause performance problems, or reduce maintainability.229230### 4. Suggestions (Consider Improving)231Improvements for code organization, performance, or developer experience.232233### 5. Positive Observations234Well-implemented patterns and good practices to acknowledge.235236### 6. Recommendations237Prioritized next steps with code examples for the most impactful improvements.238239## Best Practices240241- Keep `'use client'` boundaries as deep in the tree as possible242- Fetch data in Server Components — avoid client-side fetching for initial data243- Use parallel data fetching (`Promise.all`) to avoid request waterfalls244- Implement proper loading, error, and not-found states for every route segment245- Validate all Server Action inputs with Zod or similar libraries246- Use `revalidatePath`/`revalidateTag` instead of time-based revalidation when possible247- Scope middleware to specific routes with `config.matcher`248- Implement `generateMetadata` for dynamic pages with variable content249- Use `generateStaticParams` for static pages with known parameters250- Avoid importing server-only code in Client Components — use the `server-only` package251252## Constraints and Warnings253254- This skill targets Next.js App Router — Pages Router patterns may differ significantly255- Respect the project's Next.js version — some features are version-specific256- Do not suggest migrating from Pages Router to App Router unless explicitly requested257- Caching behavior differs between development and production — validate in production builds258- Server Actions must never expose sensitive operations without proper authentication checks259- Focus on high-confidence issues — avoid false positives on style preferences260261## References262263See the `references/` directory for detailed review checklists and pattern documentation:264- `references/app-router-patterns.md` — App Router best practices and patterns265- `references/server-components.md` — Server Component and Client Component boundary guide266- `references/performance.md` — Next.js performance optimization checklist