The use server directive tells Next.js that a function runs only on the server. This helps keep your app secure and fast by separating server code from client code.
Use server directive in NextJS
Start learning this pattern below
Jump into concepts and practice - no test required
"use server"; export async function myServerFunction() { // server-only code here }
The directive "use server"; must be the very first line in the file or function.
Functions marked with use server can be imported and called from client components as Server Actions.
"use server"; export async function fetchUserData() { const res = await fetch('https://api.example.com/user'); return res.json(); }
"use server"; export function updateDatabase() { // code to update database }
This example shows a server function getServerTime that returns the current time as a string. The client component calls this server function when the button is clicked and shows the time.
"use server"; export async function getServerTime() { return new Date().toISOString(); } // In a client component 'use client'; import { useState } from 'react'; import { getServerTime } from './serverFunctions'; export default function ShowServerTime() { const [time, setTime] = useState(''); async function fetchTime() { const serverTime = await getServerTime(); setTime(serverTime); } return ( <div> <button onClick={fetchTime} aria-label="Get server time">Get Server Time</button> {time && <p>Server time is: {time}</p>} </div> ); }
Remember to keep use server functions free of client-only code like DOM access.
Server functions can be called from client components using Next.js server actions or API routes.
use server marks functions to run only on the server.
It helps keep sensitive code secure and improves app performance.
Use it when you want to separate server logic from client logic clearly.
Practice
use server directive in Next.js?Solution
Step 1: Understand the role of
The directive marks functions to run only on the server side, not on the client.use serverStep 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 CQuick Check:
use server = server-only functions [OK]
- Thinking it enables client-side rendering
- Confusing it with CSS imports
- Assuming it shares variables globally
use server directive in Next.js?Solution
Step 1: Identify correct directive syntax
Theuse serverdirective 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 AQuick Check:
Directive as string literal = correct syntax [OK]
- Omitting quotes around use server
- Using semicolon incorrectly
- Trying to call use server as a function
"use client";
import { useState } from 'react';
export default function Page() {
const [count, setCount] = useState(0);
async function increment() {
'use server';
// server-only logic
return count + 1;
}
return setCount(count + 1)}>Count: {count};
}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 AQuick Check:
Client state updates on click = Button shows count starting at 0 and increments on click. [OK]
- Assuming server function runs automatically
- Expecting error from server function inside client
- Thinking count starts at 1
'use server'
export async function getData() {
const res = await fetch('/api/data');
return res.json();
}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 BQuick Check:
Server fetch needs absolute URL or options [OK]
- Thinking semicolon is mandatory after directive
- Believing fetch is disallowed on server
- Assuming async can't be used with use server
use server directive to keep the fetch logic server-side while exposing only safe data to the client?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 DQuick Check:
Server fetch in API route = secure data [OK]
- Trying to use use server in client components
- Fetching sensitive data directly on client
- Marking entire API route file incorrectly
