Bird
Raised Fist0
NextJSframework~10 mins

API routes vs server actions decision in NextJS - Visual Side-by-Side Comparison

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
Concept Flow - API routes vs server actions decision
Start: User triggers data operation
Decision: Use API Route or Server Action?
API Route chosen
Client calls API
API Route runs
Response sent
Client updates UI
End
This flow shows how a user-triggered data operation leads to choosing between API routes or server actions, then how each path processes and updates the UI.
Execution Sample
NextJS
export async function POST(request) {
  const data = await request.json();
  // process data
  return new Response('OK');
}

// vs

'use server';
export async function submitData(formData) {
  // process data
}
Shows a simple API route POST handler and a server action function for data submission.
Execution Table
StepTriggerPath ChosenActionResultUI Update
1User submits formDecisionCheck if server action supportedServer action supportedNo UI change yet
2DecisionServer ActionCall server action functionServer action runs on serverNo UI change yet
3Server action runsServer ActionProcess data and returnData processed successfullyUI updates with success message
4User submits formDecisionCheck if server action supportedServer action not supportedNo UI change yet
5DecisionAPI RouteClient calls API route POSTAPI route receives requestNo UI change yet
6API route runsAPI RouteProcess data and send responseResponse sent with status OKUI updates with success message
7EndBothOperation completeData handledUI reflects new state
💡 Execution stops after UI updates reflecting the data operation completion.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5After Step 6Final
pathChosenundefinedserver actionserver actionapi routeapi routefinal decision
dataProcessedfalsefalsetruefalsetruetrue
uiStateinitialinitialsuccess messageinitialsuccess messageupdated
Key Moments - 2 Insights
Why choose server actions over API routes?
Server actions run directly on the server and integrate tightly with React components, reducing client-server round trips. See execution_table rows 1-3 for how server actions handle data without extra client calls.
When must we use API routes instead of server actions?
Use API routes when you need a RESTful endpoint accessible from anywhere or when server actions are not supported, as shown in execution_table rows 4-6 where the decision falls back to API routes.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the 'pathChosen' variable after step 3?
Aserver action
Bapi route
Cundefined
Dboth
💡 Hint
Check variable_tracker row for 'pathChosen' after step 3.
At which step does the UI update with a success message when using API routes?
AStep 3
BStep 6
CStep 2
DStep 5
💡 Hint
Look at execution_table rows where UI Update column changes for API route path.
If server actions are not supported, what changes in the execution flow?
AClient calls server action anyway
BNo data operation happens
CClient calls API route instead
DUI updates without server call
💡 Hint
See execution_table rows 4 and 5 for fallback behavior.
Concept Snapshot
API routes are server endpoints called via HTTP requests, good for REST APIs and external access.
Server actions run server-side functions directly from React components, reducing client-server trips.
Choose server actions for tight integration and simpler code.
Use API routes when you need external or RESTful access.
Decision depends on support, use case, and architecture.
Full Transcript
This visual execution shows how a user-triggered data operation in Next.js leads to choosing between API routes and server actions. The decision depends on support and use case. Server actions run server-side functions directly from React components, reducing client-server communication. API routes are traditional HTTP endpoints called by the client. The execution table traces steps from user action, decision, server processing, to UI update. Variables track the chosen path, data processing state, and UI state. Key moments clarify when to pick each method. The quiz tests understanding of the flow and variable states.

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