Next.js 15 Async Cookies & Server Actions
Next.js 15 turned cookies() and headers() into asynchronous Promises. Without strict negative guardrails, AI default models call cookies() synchronously and output unvalidated Server Actions, causing instant runtime crashes.
// ❌ AI Model Default Output (Without AgentRules)
import { cookies } from "next/headers";
import { useRouter } from "next/router"; // FATAL: Pages router in App Router!
// Server Action
export async function updateUserProfile(formData: FormData) {
"use server";
// BUG 1: Synchronous call in Next.js 15 throws runtime exception!
const session = cookies().get("session_token")?.value;
// BUG 2: Direct unvalidated mutation - SQL/XSS vulnerability!
const name = formData.get("name") as string;
await db.user.update({ where: { session }, data: { name } });
}Next.js 15 App Router strictly forbids importing 'useRouter' from 'next/router'. Must import from 'next/navigation'.
In Next.js 15, cookies() returns a Promise. Calling cookies().get() throws: 'Error: cookies() should be awaited before using its value'.
Server Actions are public HTTP POST endpoints. Raw casting 'as string' allows malicious payloads and CSRF tampering.
// ✅ Guarded by 'nextjs-15-app-router' Specification
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { z } from "zod";
const ProfileSchema = z.object({
name: z.string().trim().min(2).max(50),
});
export async function updateUserProfile(formData: FormData) {
"use server";
// 1. Asynchronously read cookies (Next.js 15 standard)
const cookieStore = await cookies();
const sessionToken = cookieStore.get("session_token")?.value;
if (!sessionToken) redirect("/login");
// 2. Strict runtime schema validation
const result = ProfileSchema.safeParse({ name: formData.get("name") });
if (!result.success) return { error: result.error.flatten() };
await db.user.update({ where: { session: sessionToken }, data: result.data });
return { success: true };
}Properly awaits cookies() promise, ensuring zero runtime exceptions across Server Components and Server Actions.
Guarantees runtime data integrity and sanitization before hitting database mutations.