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
Using the 'use server' Directive in Next.js 14
📖 Scenario: You are building a simple Next.js 14 app where you want to handle a form submission on the server side using the new use server directive.This helps keep your server logic separate and secure while using React Server Components.
🎯 Goal: Create a Next.js 14 component that uses the use server directive to define a server action function. This function will handle a form submission and update a message displayed on the page.
📋 What You'll Learn
Create a React Server Component with a form
Define a server action function using the use server directive
Use the server action function as the form's action handler
Display a message updated by the server action
💡 Why This Matters
🌍 Real World
Using the 'use server' directive lets you write server-only logic in Next.js 14 apps, improving security and performance by keeping sensitive code on the server.
💼 Career
Understanding server actions and React Server Components is essential for modern Next.js development roles, enabling you to build scalable and secure web applications.
Progress0 / 4 steps
1
Create the basic React Server Component with a form
Create a React Server Component called MessageForm that returns a form with a single text input named message and a submit button labeled Send. The form should have no action yet.
NextJS
Hint
Start by writing a function named MessageForm that returns JSX with a form, input, and button.
2
Add a server action function with the 'use server' directive
Inside the MessageForm component file, define a function called handleSubmit that uses the "use server" directive at the top of its body. This function should accept a FormData parameter and extract the message field from it.
NextJS
Hint
Write an async function named handleSubmit with formData parameter. Add "use server"; at the start of the function body.
3
Connect the server action function to the form's action attribute
Modify the form element to use the handleSubmit function as its action attribute. This will make the form submit call the server action.
NextJS
Hint
Add action={handleSubmit} inside the <form> tag.
4
Add state to display the submitted message
Add a React useState hook called submittedMessage initialized to an empty string. Update the handleSubmit function to set submittedMessage to the submitted message string. Display submittedMessage below the form inside a <p> tag.
NextJS
Hint
Import useState from React. Create state variables and update the state inside handleSubmit. Show the message below the form.
Practice
(1/5)
1. What is the main purpose of the use server directive in Next.js?
easy
A. To enable client-side rendering of components.
B. To import CSS stylesheets into components.
C. To mark functions that should only run on the server for security and performance.
D. To declare global variables accessible on both client and server.
Solution
Step 1: Understand the role of use server
The directive marks functions to run only on the server side, not on the client.
Step 2: Recognize benefits
This separation helps keep sensitive code secure and improves app performance by avoiding client execution.
Final Answer:
To mark functions that should only run on the server for security and performance. -> Option C
Quick Check:
use server = server-only functions [OK]
Hint: Remember: use server means run code only on server [OK]
Common Mistakes:
Thinking it enables client-side rendering
Confusing it with CSS imports
Assuming it shares variables globally
2. Which of the following is the correct way to declare a server-only function using the use server directive in Next.js?
easy
A. 'use server'; function fetchData() { return 'data'; }
B. "use server" function fetchData() { return 'data'; }
C. use server; function fetchData() { return 'data'; }
D. use server() function fetchData() { return 'data'; }
Solution
Step 1: Identify correct directive syntax
The use server directive must be a string literal: 'use server';
Step 2: Check function declaration
The function follows normal JavaScript syntax after the directive.
Final Answer:
'use server'; function fetchData() { return 'data'; } -> Option A
Quick Check:
Directive as string literal = correct syntax [OK]
Hint: Use quotes around use server directive [OK]
Common Mistakes:
Omitting quotes around use server
Using semicolon incorrectly
Trying to call use server as a function
3. Given the code below, what will be the output when the component renders?
A. Button shows count starting at 0 and increments on click.
B. Error because server function is called inside client component.
C. Button shows count but does not update on click.
D. Button shows count starting at 1 immediately.
Solution
Step 1: Identify client and server code
The component uses "use client" so it runs on client. The increment function is marked 'use server' but is not called in this code.
Step 2: Understand state update
The button's onClick updates state locally with setCount(count + 1), so count increments on click.
Final Answer:
Button shows count starting at 0 and increments on click. -> Option A
Quick Check:
Client state updates on click = Button shows count starting at 0 and increments on click. [OK]
Hint: Server functions don't run unless explicitly called [OK]
Common Mistakes:
Assuming server function runs automatically
Expecting error from server function inside client
Thinking count starts at 1
4. What is wrong with the following Next.js server function?
'use server'
export async function getData() {
const res = await fetch('/api/data');
return res.json();
}
medium
A. Missing semicolon after 'use server' directive.
B. The fetch URL should be absolute or use Next.js fetch options.
C. Cannot use fetch inside server functions.
D. Async functions cannot be marked with 'use server'.
Solution
Step 1: Check directive syntax
Missing semicolon is not a syntax error in JavaScript, so not critical here.
Step 2: Analyze fetch usage
In server functions, fetch should use absolute URLs or Next.js fetch options to avoid errors.
Final Answer:
The fetch URL should be absolute or use Next.js fetch options. -> Option B
Quick Check:
Server fetch needs absolute URL or options [OK]
Hint: Use absolute URLs in server fetch calls [OK]
Common Mistakes:
Thinking semicolon is mandatory after directive
Believing fetch is disallowed on server
Assuming async can't be used with use server
5. You want to create a Next.js API route that uses a server-only function to fetch user data securely. Which approach correctly uses the use server directive to keep the fetch logic server-side while exposing only safe data to the client?
hard
A. Fetch data in client components and mark the fetch function with 'use server' to secure it.
B. Mark the API route file with 'use server' and call fetch directly in client components.
C. Use 'use server' in client components to fetch data and pass it to API routes.
D. Declare 'use server' inside the API route handler and call fetch there, then return safe data.
Solution
Step 1: Understand server-only logic placement
The server-only fetch logic should be inside the API route handler marked with 'use server' to keep it secure.
Step 2: Avoid client-side fetch for sensitive data
Client components should not fetch sensitive data directly or use 'use server' since it only works server-side.
Final Answer:
Declare 'use server' inside the API route handler and call fetch there, then return safe data. -> Option D
Quick Check:
Server fetch in API route = secure data [OK]
Hint: Keep fetch in API route with use server [OK]