LearnFrenzy
Sign in Take a free test

Next.js interview · Set 3 of 6

Data Fetching, Server Actions and Mutations

  • 6 follow-up questions
  • 4 key points
  • Code examples
Test yourself

Read on the server, mutate with actions

Fetch in Server Components without waterfalls, mutate with validated and authorised Server Actions, and give users instant feedback with pending and optimistic states.

  • Readingasync components and parallel fetches.
  • WritingServer Actions, validation and revalidation.
  • UXuseActionState, pending and optimistic UI.

Next.js changed how React apps load and change data: fetch directly in Server Components, and mutate with Server Actions instead of hand-written API routes. Interviewers check that you do it fast, safely and with good form UX.

1. How do you fetch data in the App Router?

Make the Server Component async and await your data source — a database client, an ORM or fetch. No useEffect, no API route in between, and secrets never reach the browser. For client-side live data (polling, user-driven filters), use a client library such as TanStack Query or SWR.

export default async function JobsPage() {
  const jobs = await db.job.findMany({ where: { open: true }, orderBy: { postedAt: 'desc' }, take: 20 });
  return <JobList jobs={jobs} />;
}

2. How do you avoid request waterfalls?

Start independent requests together with Promise.all instead of awaiting one after another, and wrap slow independent sections in their own Suspense boundaries so each streams as soon as it is ready.

export default async function ProfilePage({ params }) {
  const { id } = await params;
  const [user, orders, wallet] = await Promise.all([getUser(id), getOrders(id), getWallet(id)]);
  return <Profile user={user} orders={orders} wallet={wallet} />;
}

3. What are Server Actions?

Async functions marked with 'use server' that run on the server and can be called from forms (action={fn}) or client code. Next.js creates a secure POST endpoint for each one. They are ideal for mutations: create, update, delete — followed by revalidation or redirect.

// app/actions.ts
'use server';
import { z } from 'zod';
import { revalidatePath } from 'next/cache';

const Schema = z.object({ title: z.string().min(3), company: z.string().min(2) });

export async function createJob(prevState, formData: FormData) {
  const user = await requireUser();                         // authorise inside the action
  const parsed = Schema.safeParse(Object.fromEntries(formData));
  if (!parsed.success) return { errors: parsed.error.flatten().fieldErrors };
  await db.job.create({ data: { ...parsed.data, postedBy: user.id } });
  revalidatePath('/jobs');
  return { message: 'Job posted' };
}

4. How do you show validation errors and pending state in a form?

Use useActionState to get the action's returned state (errors, messages) and a pending flag, or useFormStatus inside a submit button. Forms with Server Actions also work before JavaScript loads (progressive enhancement).

'use client';
import { useActionState } from 'react';
import { createJob } from './actions';

export function JobForm() {
  const [state, formAction, pending] = useActionState(createJob, {});
  return (
    <form action={formAction}>
      <input name="title" />
      {state.errors?.title && <p className="error">{state.errors.title[0]}</p>}
      <input name="company" />
      <button disabled={pending}>{pending ? 'Posting…' : 'Post job'}</button>
      {state.message && <p role="status">{state.message}</p>}
    </form>
  );
}

5. Are Server Actions secure by default?

They are public HTTP endpoints, so treat them like API routes: authenticate and authorise inside every action, validate all input with a schema, never trust hidden form fields for permissions, and return safe error messages. Next.js adds protections (encrypted action ids, origin checks), but authorisation is your job.


6. How do you implement optimistic UI?

useOptimistic shows the expected result immediately (a new comment, a ticked task) while the Server Action runs; React reconciles with the real result when it completes or rolls back on error.

const [optimisticTodos, addOptimistic] = useOptimistic(todos, (current, newTodo) => [...current, { ...newTodo, pending: true }]);

async function add(formData) {
  const todo = { id: crypto.randomUUID(), title: formData.get('title') };
  addOptimistic(todo);
  await createTodo(todo);        // Server Action
}

7. When do you still need Route Handlers instead of Server Actions?

For endpoints called by other clients — mobile apps, webhooks from payment providers, third-party integrations — and for GET APIs, file downloads, streaming responses or custom HTTP behaviour. Server Actions are for your own app's UI mutations.

// app/api/webhooks/razorpay/route.ts
export async function POST(req: Request) {
  const body = await req.text();
  if (!verifySignature(body, req.headers.get('x-razorpay-signature'))) {
    return new Response('Invalid signature', { status: 400 });
  }
  await markOrderPaid(JSON.parse(body));
  return Response.json({ ok: true });
}

8. How do you redirect after a mutation?

Call redirect('/jobs/' + id) inside the Server Action after the work and revalidation; it throws internally, so call it outside try/catch or rethrow. Use revalidatePath first so the destination shows fresh data.


Remember

Key points

  • Promise.all for independent data

    Avoid waterfalls.

  • Actions are public endpoints

    Authorise and validate inside.

  • Revalidate after mutating

    Then redirect if needed.

  • Route Handlers for outsiders

    Webhooks, mobile and public APIs.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 Can you call a Server Action from a button onClick? Basic

    Yes — import it in a client component and call it inside a transition (startTransition) or an async handler.

  2. 2 How do you pass extra data to a Server Action? Intermediate

    Use action.bind(null, id) to pre-fill arguments, or hidden inputs for non-sensitive values.

  3. 3 What happens if a Server Action throws? Intermediate

    The nearest error boundary catches it; prefer returning error state for expected failures and throwing only for unexpected ones.

  4. 4 How do you upload files with Server Actions? Intermediate

    Read the File from FormData, validate type and size, and stream it to storage (S3, Cloud Storage); for large files use direct uploads with signed URLs.

  5. 5 Can Server Components read cookies? Basic

    Yes, with await cookies() from next/headers — which makes the route dynamic. Setting cookies is done in Server Actions or Route Handlers.

  6. 6 How do you de-duplicate a database call used in several components? Advanced

    Wrap the function with React's cache() so repeated calls in one request share the result, or use 'use cache' for persistent caching.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links