Bird
Raised Fist0
NextJSframework~20 mins

API routes vs server actions decision in NextJS - Practice Questions

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Next.js Server Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
When to prefer Server Actions over API Routes in Next.js?

In Next.js 14+, you want to handle a form submission that updates user data and immediately reflects changes on the page without extra client-side fetching. Which approach is best?

AUse static generation with incremental static regeneration to update user data.
BUse an API route to handle the form submission, then fetch updated data on the client.
CUse client-side fetch to call an external API and update state manually.
DUse a Server Action to handle the form submission directly, allowing immediate server-side updates and UI refresh.
Attempts:
2 left
💡 Hint

Think about how Server Actions can simplify server communication and UI updates without extra client fetches.

component_behavior
intermediate
2:00remaining
What happens when a Server Action throws an error?

Consider a Server Action in Next.js that throws an error during execution. What is the expected behavior in the client component that called it?

AThe error is thrown back to the client, and you must handle it explicitly to show feedback.
BThe error causes the entire page to crash with no recovery.
CThe error is caught and displayed automatically in the UI without extra code.
DThe Server Action retries automatically until it succeeds.
Attempts:
2 left
💡 Hint

Think about error handling responsibility in Server Actions.

📝 Syntax
advanced
2:00remaining
Identify the correct Server Action syntax in Next.js 14+

Which of the following code snippets correctly defines a Server Action in Next.js 14+?

NextJS
export async function updateUser(data) {
  'use server';
  // update logic
}
Aexport async function updateUser(data) { 'use server'; /* update logic */ }
Bexport async function updateUser(data) { 'use client'; /* update logic */ }
Cexport async function updateUser(data) { /* update logic */ }
Dexport function updateUser(data) { 'use server'; /* update logic */ }
Attempts:
2 left
💡 Hint

Server Actions require a special directive to mark them as server-only.

🔧 Debug
advanced
2:00remaining
Why does this API route not update the database?

You have this Next.js API route code:

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const data = req.body;
    updateDatabase(data);
    res.status(200).json({ success: true });
  } else {
    res.status(405).end();
  }
}

Why might the database not update as expected?

ABecause req.body is undefined in API routes by default.
BBecause updateDatabase is asynchronous but not awaited, so the response ends before update completes.
CBecause the API route must be named api.js to work.
DBecause res.status(200) must be called after res.json.
Attempts:
2 left
💡 Hint

Consider asynchronous function calls and response timing.

state_output
expert
3:00remaining
What is the rendered output after this Server Action updates state?

Given this React Server Component with a Server Action that updates a counter:

import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  async function increment() {
    'use server';
    setCount(count + 1);
  }

  return (
    

Count: {count}

); }

What will the user see after clicking Increment once?

ACount: 0 (no change)
BCount: 1
CAn error because setCount cannot be used in Server Actions
DCount increments but resets to 0 on every render
Attempts:
2 left
💡 Hint

Think about React state and Server Actions interaction.

Practice

(1/5)
1. What is the main difference between Next.js API routes and server actions?
easy
A. API routes and server actions are exactly the same in Next.js.
B. API routes run only on the client; server actions run only on the server.
C. API routes create separate endpoints; server actions call server code directly from components.
D. API routes are used for styling; server actions handle routing.

Solution

  1. Step 1: Understand API routes purpose

    API routes create separate API endpoints that the client can call to communicate with the server.
  2. Step 2: Understand server actions purpose

    Server actions allow calling server code directly from React components without creating separate endpoints.
  3. Final Answer:

    API routes create separate endpoints; server actions call server code directly from components. -> Option C
  4. Quick Check:

    API routes vs server actions difference = D [OK]
Hint: API routes = endpoints; server actions = direct calls [OK]
Common Mistakes:
  • Thinking API routes run on client side
  • Confusing server actions with styling or routing
  • Believing API routes and server actions are identical
2. Which of the following is the correct way to define a server action in Next.js?
easy
A. export default function handler(req, res) { /* server code */ }
B. export async function actionName() { /* server code */ }
C. function actionName() { return
Server Action
}
D. const actionName = () => fetch('/api/data')

Solution

  1. Step 1: Identify server action syntax

    Server actions are defined as exported async functions that run on the server.
  2. Step 2: Compare with API route syntax

    API routes use a default export function with (req, res) parameters, not named async functions.
  3. Final Answer:

    export async function actionName() { /* server code */ } -> Option B
  4. Quick Check:

    Server action syntax = B [OK]
Hint: Server actions use named async functions exported directly [OK]
Common Mistakes:
  • Using default export with req, res (API route style)
  • Writing server actions as React components
  • Calling fetch inside server action definition
3. Given this Next.js server action code, what will be the output when called from a component?
export async function addNumbers(a, b) {
  return a + b;
}
medium
A. Returns a Promise resolving to the sum of a and b.
B. Returns undefined because server actions cannot return values.
C. Throws a syntax error due to missing parameters.
D. Returns a string concatenation of a and b.

Solution

  1. Step 1: Analyze the server action function

    The function is async and returns the sum of a and b, which is a number.
  2. Step 2: Understand async function return

    Async functions return a Promise that resolves to the returned value, here the sum.
  3. Final Answer:

    Returns a Promise resolving to the sum of a and b. -> Option A
  4. Quick Check:

    Async function returns Promise with sum = A [OK]
Hint: Async server actions return Promises with results [OK]
Common Mistakes:
  • Thinking server actions cannot return values
  • Confusing number addition with string concatenation
  • Assuming syntax error due to parameters
4. You wrote this API route in Next.js but it throws an error:
export async function handler(req, res) {
  res.status(200).json({ message: 'Hello' });
}

What is the error and how to fix it?
medium
A. Response method json is invalid; use send instead.
B. Should use server action syntax instead of API route syntax.
C. Function must not be async in API routes.
D. Missing default export; change to export default async function handler(req, res).

Solution

  1. Step 1: Identify API route export requirement

    API routes require a default export function to handle requests.
  2. Step 2: Fix export statement

    Change named export to default export: export default async function handler(req, res).
  3. Final Answer:

    Missing default export; change to export default async function handler(req, res). -> Option D
  4. Quick Check:

    API route default export required = C [OK]
Hint: API routes need default export function [OK]
Common Mistakes:
  • Using named export instead of default export
  • Confusing API routes with server actions syntax
  • Incorrect response method usage
5. You want to build a Next.js app that needs a public API for multiple clients and also some simple server logic tightly integrated with components. Which approach should you choose?
hard
A. Use API routes for the public API and server actions for simple server logic inside components.
B. Use only server actions for everything to keep code simple.
C. Use only API routes for all server logic to avoid confusion.
D. Use client-side fetching only; avoid server code.

Solution

  1. Step 1: Analyze app needs

    The app requires a public API accessible by multiple clients and simple server logic integrated with components.
  2. Step 2: Match features to approaches

    API routes are best for broad public APIs; server actions are ideal for simple, direct server calls from components.
  3. Final Answer:

    Use API routes for the public API and server actions for simple server logic inside components. -> Option A
  4. Quick Check:

    Public API + integrated logic = A [OK]
Hint: Public API = API routes; simple logic = server actions [OK]
Common Mistakes:
  • Using only server actions for public APIs
  • Using only API routes for simple component logic
  • Avoiding server code when needed