Server Actions and Route Handlers Questions
What is a Server Action and how is it called?
An async function marked 'use server' that runs on the server. Next.js exposes it as a POST endpoint with an id. You call it from <form action={fn}> (works without JS), from event handlers, or via useActionState. After mutating, call revalidatePath/revalidateTag; the updated UI comes back in the same response.
Are Server Actions secure by default?
No. They are public HTTP endpoints; anyone can call them with any arguments. Next.js adds Origin checks and unguessable, unused-action-eliminated ids, but you must still: authenticate and authorise inside every action, validate input (Zod), and never trust ids from the client without an ownership check.
Explain useActionState, useFormStatus and useOptimistic.
useActionState(action, initial)returns[state, formAction, pending]; the action receives(prevState, formData)and its return value becomes the new state (errors, messages).useFormStatus()(react-dom) givespendingto components inside a form, e.g. a submit button.useOptimistic(state)shows a temporary state during an async action, then falls back to the real state when it finishes.
When would you use a Route Handler instead of a Server Action?
Route Handlers (app/api/.../route.ts) are for HTTP APIs consumed by others: mobile apps, third parties, webhooks (Razorpay/Stripe), file downloads, RSS/CSV, cron calls, or GET endpoints with caching headers. Server Actions are for mutations triggered by your own UI.
export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
return Response.json({ id });
}What is middleware used for, and what changed in Next.js 16?
middleware.ts runs before routing for matched paths: redirects, rewrites, auth cookie checks, headers, A/B buckets, locale detection. Keep it fast (no heavy DB calls) and still check auth near the data. In Next.js 16 it is renamed proxy.ts (function proxy) and runs on the Node.js runtime by default; middleware.ts is deprecated.