This skill guides advanced Next.js App Router patterns focusing on server actions, route handlers, parallel routes, cookies, and streaming for robust web apps.
npx playbooks add skill wsimmonds/claude-nextjs-skills --skill nextjs-advanced-routing
Provide comprehensive guidance for advanced Next.js App Router features including Route Handlers (API routes), Parallel Routes, Intercepting Routes, Server Actions, error handling, draft mode, and streaming with Suspense.
any TypeCRITICAL RULE: This codebase has @typescript-eslint/no-explicit-any enabled. Using any will cause build failures.
❌ WRONG:
function handleSubmit(e: any) { ... }
const data: any[] = [];
✅ CORRECT:
function handleSubmit(e: React.FormEvent<HTMLFormElement>) { ... }
const data: string[] = [];
// Page props
function Page({ params }: { params: { slug: string } }) { ... }
function Page({ searchParams }: { searchParams: { [key: string]: string | string[] | undefined } }) { ... }
// Form events
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { ... }
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { ... }
// Server actions
async function myAction(formData: FormData) { ... }
Use this skill when:
When work requirements mention a specific filename, follow that instruction exactly. If no name is given, pick the option that best matches the project conventions—app/actions.ts is a safe default for collections of actions, while app/action.ts works for a single form handler.
action.ts and actions.tsaction.ts for a single action, and actions.ts for a group of related actions.Location guidelines
app/ directory so they can participate in the App Router tree.lib/ or utils/ unless they are triggered from multiple distant routes and remain server-only utilities.Example placement
app/
├── actions.ts ← Shared actions that support multiple routes
└── dashboard/
└── action.ts ← Route-specific action colocated with a single page
// app/action.ts (single-action example)
'use server';
export async function submitForm(formData: FormData) {
const name = formData.get('name') as string;
// Process the form
console.log('Submitted:', name);
}
// app/actions.ts (multiple related actions)
'use server';
export async function createPost(formData: FormData) {
// ...
}
export async function deletePost(id: string) {
// ...
}
Remember: When a project requirement spells out an exact filename, mirror it precisely.
This is a TypeScript requirement, not optional. Even if you see code that returns data from form actions, that code is WRONG.
When using form action attribute: <form action={serverAction}>
return undefined or return null❌ WRONG (causes build error):
export async function saveForm(formData: FormData) {
'use server';
const name = formData.get('name') as string;
if (!name) throw new Error('Name required');
await db.save(name);
return { success: true }; // ❌ BUILD ERROR: Type mismatch
}
// In component:
<form action={saveForm}> {/* ❌ Expects void function */}
<input name="name" />
</form>
✅ CORRECT - Option 1 (Simple form action, no response):
export async function saveForm(formData: FormData) {
'use server';
const name = formData.get('name') as string;
// Validate - throw errors instead of returning them
if (!name) throw new Error('Name required');
await db.save(name);
revalidatePath('/'); // Trigger UI update
// No return statement - returns void implicitly
}
// In component:
<form action={saveForm}>
<input name="name" required />
<button type="submit">Save</button>
</form>
✅ CORRECT - Option 2 (With useActionState for feedback):
export async function saveForm(prevState: any, formData: FormData) {
'use server';
const name = formData.get('name') as string;
if (!name) return { error: 'Name required' };
await db.save(name);
return { success: true, message: 'Saved!' }; // ✅ OK with useActionState
}
// In component:
'use client';
const [state, action] = useActionState(saveForm, null);
return (
<form action={action}>
<input name="name" required />
<button type="submit">Save</button>
{state?.error && <p>{state.error}</p>}
{state?.success && <p>{state.message}</p>}
</form>
);
The key rule: <form action={...}> expects void. If you need to return data, use useActionState.
Route Handlers replace API Routes from the Pages Router. Create them in route.ts or route.js files.
// app/api/hello/route.ts
export async function GET(request: Request) {
return Response.json({ message: 'Hello World' });
}
export async function POST(request: Request) {
const body = await request.json();
return Response.json({
message: 'Data received',
data: body
});
}
// app/api/items/route.ts
export async function GET(request: Request) { }
export async function POST(request: Request) { }
export async function PUT(request: Request) { }
export async function PATCH(request: Request) { }
export async function DELETE(request: Request) { }
export async function HEAD(request: Request) { }
export async function OPTIONS(request: Request) { }
// app/api/posts/[id]/route.ts
export async function GET(
request: Request,
{ params }: { params: { id: string } }
) {
const id = params.id;
const post = await db.posts.findUnique({ where: { id } });
return Response.json(post);
}
export async function DELETE(
request: Request,
{ params }: { params: { id: string } }
) {
await db.posts.delete({ where: { id: params.id } });
return Response.json({ success: true });
}
// app/api/profile/route.ts
import { cookies, headers } from 'next/headers';
export async function GET(request: Request) {
// Access headers
const headersList = await headers();
const authorization = headersList.get('authorization');
// Access cookies
const cookieStore = await cookies();
const sessionToken = cookieStore.get('session-token');
if (!sessionToken) {
return Response.json({ error: 'Unauthorized' }, { status: 401 });
}
const user = await fetchUser(sessionToken.value);
return Response.json(user);
}
// app/api/login/route.ts
import { cookies } from 'next/headers';
export async function POST(request: Request) {
const { email, password } = await request.json();
const token = await authenticate(email, password);
if (!token) {
return Response.json({ error: 'Invalid credentials' }, { status: 401 });
}
// Set cookie
const cookieStore = await cookies();
cookieStore.set('session-token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60 * 24 * 7, // 1 week
path: '/',
});
return Response.json({ success: true });
}
// app/api/public/route.ts
export async function GET(request: Request) {
const data = await fetchData();
return Response.json(data, {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
});
}
export async function OPTIONS(request: Request) {
return new Response(null, {
status: 204,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
});
}
// app/api/stream/route.ts
export async function GET() {
const encoder = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
for (let i = 0; i < 10; i++) {
controller.enqueue(encoder.encode(`data: ${i}\n\n`));
await new Promise(resolve => setTimeout(resolve, 1000));
}
controller.close();
},
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
},
});
}
Server Actions enable server-side mutations without creating API endpoints.
// app/actions.ts
'use server';
import { revalidatePath } from 'next/cache';
export async function createPost(formData: FormData) {
const title = formData.get('title') as string;
const content = formData.get('content') as string;
const post = await db.posts.create({
data: { title, content },
});
revalidatePath('/posts');
// No return statement - Server Actions with forms should return void
}
Note: See "Using Server Actions in Forms" section below for patterns that return data vs. those that don't.
File Naming Precision:
action.ts”), mirror it exactly.action.ts (singular) or actions.ts (plural)—choose the one that matches the brief or existing code.app/action.ts or app/actions.ts.Two Patterns for 'use server' Directive:
Pattern 1: File-level (recommended for multiple actions):
// app/actions.ts
'use server'; // At the top - ALL exports are server actions
export async function createPost(formData: FormData) { ... }
export async function updatePost(formData: FormData) { ... }
export async function deletePost(postId: string) { ... }
Pattern 2: Function-level (for single action or mixed file):
// app/action.ts or any file
export async function createPost(formData: FormData) {
'use server'; // Inside the function - ONLY this function is a server action
const title = formData.get('title') as string;
await db.posts.create({ data: { title } });
}
Client Component Calling Server Action:
When a client component needs to call a server action (e.g., onClick, form submission):
✅ CORRECT Pattern:
// app/actions.ts - Server Actions file
'use server';
import { cookies } from 'next/headers';
export async function updateUserPreference(key: string, value: string) {
const cookieStore = await cookies();
cookieStore.set(key, value);
// Or perform other server-side operations
await db.userSettings.update({ [key]: value });
}
// app/InteractiveButton.tsx - Client Component
'use client';
import { updateUserPreference } from './actions';
export default function InteractiveButton() {
const handleClick = () => {
updateUserPreference('theme', 'dark');
};
return (
<button onClick={handleClick}>
Update Preference
</button>
);
}
❌ WRONG - Mixing 'use server' and 'use client' in same file:
// app/CookieButton.tsx
'use client'; // This file is a client component
export async function setCookie() {
'use server'; // ERROR! Can't have server actions in client component file
// ...
}
CRITICAL: When using form action attribute directly, the Server Action MUST return void (nothing). Do NOT return { success: true } or any object.
VALIDATION RULE: Check all inputs and throw errors if validation fails. Do NOT return error objects.
⚠️ IMPORTANT: Even if you see example code in the codebase that returns { success: true } from a form action, do NOT copy that pattern. That code is an anti-pattern. Always:
Correct pattern for form actions:
// app/actions.ts
'use server';
export async function createPost(formData: FormData) {
const title = formData.get('title') as string;
const content = formData.get('content') as string;
// Validate
if (!title || !content) {
throw new Error('Title and content are required');
}
// Save to database
await db.posts.create({ data: { title, content } });
// Revalidate or redirect - no return needed
revalidatePath('/posts');
}
// app/posts/new/page.tsx
import { createPost } from '@/app/actions';
export default function NewPost() {
return (
<form action={createPost}>
<input name="title" placeholder="Title" required />
<textarea name="content" placeholder="Content" required />
<button type="submit">Create Post</button>
</form>
);
}
When you need to display success/error messages, use useActionState:
// app/actions.ts
'use server';
export async function createPost(formData: FormData) {
const title = formData.get('title') as string;
const content = formData.get('content') as string;
if (!title || !content) {
return { success: false, error: 'Title and content required' };
}
const post = await db.posts.create({ data: { title, content } });
return { success: true, post };
}
// app/posts/new/page.tsx
'use client';
import { createPost } from '@/app/actions';
import { useActionState } from 'react';
export default function NewPost() {
const [state, action, isPending] = useActionState(createPost, null);
return (
<form action={action}>
<input name="title" placeholder="Title" required />
<textarea name="content" placeholder="Content" required />
<button type="submit" disabled={isPending}>
{isPending ? 'Creating...' : 'Create Post'}
</button>
{state?.error && <p style={{ color: 'red' }}>{state.error}</p>}
{state?.success && <p style={{ color: 'green' }}>Post created!</p>}
</form>
);
}
Key difference:
revalidatePathuseActionState, Server Action returns data for displayWhen validating multiple required fields, check them all together and throw if any are missing:
'use server';
export async function saveContactMessage(formData: FormData) {
const name = formData.get('name') as string;
const email = formData.get('email') as string;
const message = formData.get('message') as string;
// Validate all fields - throw if any are missing
if (!name || !email || !message) {
throw new Error('All fields are required');
}
// Save to database
console.log('Saving contact message:', { name, email, message });
// No return - returns void implicitly
}
This will:
// app/actions.ts
'use server';
export async function updateUsername(userId: string, username: string) {
await db.users.update({
where: { id: userId },
data: { username },
});
return { success: true };
}
// app/components/UsernameForm.tsx
'use client';
import { updateUsername } from '@/app/actions';
import { useState } from 'react';
export default function UsernameForm({ userId }: { userId: string }) {
const [username, setUsername] = useState('');
const [loading, setLoading] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
await updateUsername(userId, username);
setLoading(false);
};
return (
<form onSubmit={handleSubmit}>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="New username"
/>
<button type="submit" disabled={loading}>
{loading ? 'Updating...' : 'Update'}
</button>
</form>
);
}
When using form actions directly, throw errors for validation failures (don't return error objects):
// app/actions.ts
'use server';
import { revalidatePath } from 'next/cache';
export async function createPost(formData: FormData) {
const title = formData.get('title') as string;
const content = formData.get('content') as string;
// Validation - throw error if invalid
if (!title || !content) {
throw new Error('Title and content are required');
}
if (title.length > 100) {
throw new Error('Title must be less than 100 characters');
}
if (content.length < 10) {
throw new Error('Content must be at least 10 characters');
}
// Save to database
const post = await db.posts.create({
data: { title, content },
});
revalidatePath('/posts');
// No return - form actions return void
}
For returning validation state: If you need to return validation errors or show them in the UI, use useActionState (Pattern 2 above) instead.
// app/actions.ts
'use server';
import { cookies } from 'next/headers';
export async function setTheme(theme: 'light' | 'dark') {
const cookieStore = await cookies();
cookieStore.set('theme', theme, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60 * 24 * 365, // 1 year
path: '/',
});
return { success: true };
}
// app/actions.ts
'use server';
import { revalidatePath, revalidateTag } from 'next/cache';
import { redirect } from 'next/navigation';
export async function deletePost(postId: string) {
await db.posts.delete({ where: { id: postId } });
// Revalidate specific path
revalidatePath('/posts');
// Or revalidate by cache tag
revalidateTag('posts');
// Redirect after deletion
redirect('/posts');
}
Before implementing parallel routes, identify WHERE they should live in your route structure.
Key Question: Is this feature for a specific page/section, or for the entire application?
**When the requiremen
Weekly roundup of top Claude Code skills, MCP servers, and AI coding tips.