API routes and server actions both let your Next.js app talk to the server. Choosing the right one helps your app work better and be easier to build.
API routes vs server actions decision in NextJS
Start learning this pattern below
Jump into concepts and practice - no test required
API Route example: // pages/api/hello.js export default function handler(req, res) { res.status(200).json({ message: 'Hello from API route!' }) } Server Action example: 'use server' export async function addData(data) { // server logic here return 'Data added' }
API routes live in the pages/api folder and act like normal API endpoints.
Server actions are functions marked with 'use server' and can be called directly from components.
// API route example export default function handler(req, res) { if (req.method === 'POST') { res.status(200).json({ success: true }) } else { res.status(405).end() } }
'use server' export async function saveUser(user) { // save user to database return 'User saved' }
This example shows a server action greet called from a React component. When you click the button, it calls the server action and shows the greeting.
// app/actions.js 'use server' export async function greet(name) { return `Hello, ${name}!` } // app/page.jsx 'use client' import { useState } from 'react' import { greet } from './actions' export default function Page() { const [message, setMessage] = useState('') async function handleClick() { const result = await greet('Friend') setMessage(result) } return ( <main> <button onClick={handleClick}>Greet</button> <p>{message}</p> </main> ) }
Use API routes when you want a traditional REST or JSON API accessible from anywhere.
Use server actions to keep server logic close to components and simplify data handling.
Server actions require Next.js 14+ and App Router setup.
API routes create separate API endpoints for client-server communication.
Server actions let you call server code directly from components without extra endpoints.
Choose based on your app's needs: API routes for broad API use, server actions for simpler, integrated server calls.
Practice
Solution
Step 1: Understand API routes purpose
API routes create separate API endpoints that the client can call to communicate with the server.Step 2: Understand server actions purpose
Server actions allow calling server code directly from React components without creating separate endpoints.Final Answer:
API routes create separate endpoints; server actions call server code directly from components. -> Option CQuick Check:
API routes vs server actions difference = D [OK]
- Thinking API routes run on client side
- Confusing server actions with styling or routing
- Believing API routes and server actions are identical
Solution
Step 1: Identify server action syntax
Server actions are defined as exported async functions that run on the server.Step 2: Compare with API route syntax
API routes use a default export function with (req, res) parameters, not named async functions.Final Answer:
export async function actionName() { /* server code */ } -> Option BQuick Check:
Server action syntax = B [OK]
- Using default export with req, res (API route style)
- Writing server actions as React components
- Calling fetch inside server action definition
export async function addNumbers(a, b) {
return a + b;
}Solution
Step 1: Analyze the server action function
The function is async and returns the sum of a and b, which is a number.Step 2: Understand async function return
Async functions return a Promise that resolves to the returned value, here the sum.Final Answer:
Returns a Promise resolving to the sum of a and b. -> Option AQuick Check:
Async function returns Promise with sum = A [OK]
- Thinking server actions cannot return values
- Confusing number addition with string concatenation
- Assuming syntax error due to parameters
export async function handler(req, res) {
res.status(200).json({ message: 'Hello' });
}What is the error and how to fix it?
Solution
Step 1: Identify API route export requirement
API routes require a default export function to handle requests.Step 2: Fix export statement
Change named export to default export:export default async function handler(req, res).Final Answer:
Missing default export; change toexport default async function handler(req, res). -> Option DQuick Check:
API route default export required = C [OK]
- Using named export instead of default export
- Confusing API routes with server actions syntax
- Incorrect response method usage
Solution
Step 1: Analyze app needs
The app requires a public API accessible by multiple clients and simple server logic integrated with components.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.Final Answer:
Use API routes for the public API and server actions for simple server logic inside components. -> Option AQuick Check:
Public API + integrated logic = A [OK]
- Using only server actions for public APIs
- Using only API routes for simple component logic
- Avoiding server code when needed
