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
Choosing Between API Routes and Server Actions in Next.js
📖 Scenario: You are building a simple Next.js app that lets users submit feedback. You want to decide whether to use API routes or server actions to handle the feedback submission.
🎯 Goal: Build a Next.js component that collects user feedback and sends it to the server using either an API route or a server action. Learn how to set up both methods and understand when to use each.
📋 What You'll Learn
Create a feedback form component with a textarea and submit button
Set up an API route to receive feedback data
Create a server action to handle feedback submission
Implement the feedback submission using both API route and server action methods
💡 Why This Matters
🌍 Real World
Feedback forms are common in websites and apps to collect user opinions or bug reports. Knowing how to handle form submissions with API routes or server actions helps build efficient and modern Next.js applications.
💼 Career
Understanding API routes and server actions is essential for Next.js developers. It helps in building scalable backend logic and choosing the right approach for server communication.
Progress0 / 4 steps
1
Create the feedback form component
Create a React functional component called FeedbackForm with a textarea for user feedback and a button to submit. Use useState to store the feedback text in a variable called feedback.
NextJS
Hint
Use useState to create feedback and setFeedback. Add a textarea with value and onChange to update the state.
2
Set up an API route to receive feedback
Create a new API route file at app/api/feedback/route.js. Export an async function called POST that accepts a request parameter. Inside, parse the JSON body to get feedback and return a JSON response with { message: 'Feedback received' }.
NextJS
Hint
Use await request.json() to get the data. Extract feedback from it. Return a JSON response with a success message.
3
Add server action to handle feedback submission
In the FeedbackForm component, create an async function called handleSubmit that takes an event parameter. Prevent default form submission. Use the Fetch API to POST the feedback state to /api/feedback as JSON. Attach handleSubmit to the form's onSubmit event.
NextJS
Hint
Prevent the default form action. Use fetch to send a POST request with JSON containing feedback. Attach handleSubmit to the form.
4
Implement server action for feedback submission
Create a server action function called submitFeedback in the FeedbackForm component. It should accept a FormData parameter, extract the feedback field, and simulate saving it by returning a success message string. Update the form to use action={submitFeedback} and change the textarea to have a name attribute of feedback. Remove the handleSubmit function and onSubmit handler.
NextJS
Hint
Define submitFeedback to get feedback from formData and return a success string. Use action={submitFeedback} on the form and add name="feedback" to the textarea. Remove previous submit handler.
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
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 C
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
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 B
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
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 A
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:
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
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 to export default async function handler(req, res). -> Option D
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
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 A
Quick Check:
Public API + integrated logic = A [OK]
Hint: Public API = API routes; simple logic = server actions [OK]