Bird
Raised Fist0
NextJSframework~20 mins

Use server directive in NextJS - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Server Directive Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this server component?

Consider this Next.js server component using the use server directive:

"use server";

export default async function Greeting() {
  const name = await fetchName();
  return <h1>Hello, {name}!</h1>;
}

async function fetchName() {
  return "Alice";
}

What will this component render on the page?

NextJS
"use server";

export default async function Greeting() {
  const name = await fetchName();
  return <h1>Hello, {name}!</h1>;
}

async function fetchName() {
  return "Alice";
}
A<h1>Hello, undefined!</h1>
B<h1>Hello, Alice!</h1>
CError: fetchName is not defined
D<h1>Hello, {name}!</h1>
Attempts:
2 left
💡 Hint

Remember that server components can await async functions and render their results directly.

📝 Syntax
intermediate
2:00remaining
Which option correctly uses the use server directive?

Which of the following Next.js component snippets correctly applies the use server directive?

A
export default function MyComponent() {
  return &lt;p&gt;Server component&lt;/p&gt;;
}
"use server";
B
export default function MyComponent() {
  "use server";
  return &lt;p&gt;Server component&lt;/p&gt;;
}
C
export default function MyComponent() {
  return &lt;p&gt;Server component&lt;/p&gt;;
}
// use server
D
"use server";

export default function MyComponent() {
  return &lt;p&gt;Server component&lt;/p&gt;;
}
Attempts:
2 left
💡 Hint

The use server directive must be the first statement in the file or component.

state_output
advanced
2:00remaining
What is the value of count after this server action?

Given this Next.js server component with a server action:

"use server";

import { useState } from 'react';

let count = 0;

export default function Counter() {
  async function increment() {
    count += 1;
  }

  return (
    <button onClick={increment}>Clicked {count} times</button>
  );
}

What will be the value of count after clicking the button 3 times?

NextJS
"use server";

import { useState } from 'react';

let count = 0;

export default function Counter() {
  async function increment() {
    count += 1;
  }

  return (
    <button onClick={increment}>Clicked {count} times</button>
  );
}
A0
BNaN
CError: count is not reactive
D3
Attempts:
2 left
💡 Hint

Remember server components do not keep state between renders on the client.

🔧 Debug
advanced
2:00remaining
Why does this server action cause a runtime error?

Examine this Next.js server component:

"use server";

export default function Form() {
  async function submit(data) {
    await saveData(data);
  }

  return (
    <form action={submit}>
      <input name="text" />
      <button type="submit">Send</button>
    </form>
  );
}

async function saveData(data) {
  console.log(data.text.toUpperCase());
}

When submitting the form, a runtime error occurs. What is the cause?

NextJS
"use server";

export default function Form() {
  async function submit(data) {
    await saveData(data);
  }

  return (
    <form action={submit}>
      <input name="text" />
      <button type="submit">Send</button>
    </form>
  );
}

async function saveData(data) {
  console.log(data.text.toUpperCase());
}
Asubmit function is missing 'use server' directive
BsaveData is not async
Cdata.text is undefined because form data is a FormData object, not a plain object
Dinput element lacks a value attribute
Attempts:
2 left
💡 Hint

Check the type of data received by the server action.

🧠 Conceptual
expert
2:00remaining
Which statement about the use server directive is TRUE?

Choose the correct statement about the use server directive in Next.js:

AIt marks a component or function to run only on the server and allows using server-only APIs.
BIt enables client-side state management inside server components.
CIt automatically converts client components to server components at build time.
DIt allows server components to directly access browser APIs like <code>window</code>.
Attempts:
2 left
💡 Hint

Think about where server components run and what APIs they can access.

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

  1. Step 1: Understand the role of use server

    The directive marks functions to run only on the server side, not on the client.
  2. Step 2: Recognize benefits

    This separation helps keep sensitive code secure and improves app performance by avoiding client execution.
  3. Final Answer:

    To mark functions that should only run on the server for security and performance. -> Option C
  4. 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

  1. Step 1: Identify correct directive syntax

    The use server directive must be a string literal: 'use server';
  2. Step 2: Check function declaration

    The function follows normal JavaScript syntax after the directive.
  3. Final Answer:

    'use server'; function fetchData() { return 'data'; } -> Option A
  4. 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?
"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};
}
medium
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

  1. 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.
  2. Step 2: Understand state update

    The button's onClick updates state locally with setCount(count + 1), so count increments on click.
  3. Final Answer:

    Button shows count starting at 0 and increments on click. -> Option A
  4. 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

  1. Step 1: Check directive syntax

    Missing semicolon is not a syntax error in JavaScript, so not critical here.
  2. Step 2: Analyze fetch usage

    In server functions, fetch should use absolute URLs or Next.js fetch options to avoid errors.
  3. Final Answer:

    The fetch URL should be absolute or use Next.js fetch options. -> Option B
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    Declare 'use server' inside the API route handler and call fetch there, then return safe data. -> Option D
  4. Quick Check:

    Server fetch in API route = secure data [OK]
Hint: Keep fetch in API route with use server [OK]
Common Mistakes:
  • Trying to use use server in client components
  • Fetching sensitive data directly on client
  • Marking entire API route file incorrectly