Skip to article content
LESSON 08 / 28

Server and client module boundaries

Place code by dependency and trust boundaries so interactive islands do not accidentally pull privileged or expensive modules into the browser.

What you will be able to do

  • Trace the transitive client import graph.
  • Compose server-rendered children with client interaction.
  • Keep private data out of serialized props and browser bundles.

A directive changes a module boundary

use client marks an entry into the client module graph. Modules imported by that entry must be compatible with the client environment. This is a dependency rule, not a visual rule saying everything nested below a colored box becomes client code. A server page can render an interactive component without turning its own database read into browser code. The distinction becomes clear when you draw imports separately from rendered children.

For a catalogue, keep data access and permission decisions in server code. Place use client on the small quantity control that needs state and an event handler. If that control imports a barrel file that also imports a database client, the boundary is no longer small or safe. Inspect transitive dependencies and use server-only markers for privileged modules so invalid imports fail early rather than relying only on naming conventions.

Pass rendered children instead of importing server work

A client wrapper can receive server-rendered children. The server constructs those children and hands their representation through the boundary. The client wrapper can toggle visibility or provide a context around them without importing the server component implementation. This pattern lets an accordion or provider surround content while keeping data access on the server.

Do not assume that hiding server-rendered children means their server computation is delayed until a click. If the server already rendered them to construct the response, hiding them only changes presentation. To defer a later operation, design an actual later request or a suitable framework data flow. In interviews, explain what has already run before the browser receives the tree rather than describing the UI from appearance alone.

Client module

app/catalog/Expandable.tsx
'use client';
import { useState, type ReactNode } from 'react';
export default function Expandable({ children }: { children: ReactNode }) {
  const [open, setOpen] = useState(false);
  return <section>
    <button aria-expanded={open} onClick={() => setOpen(value => !value)}>
      {open ? 'Hide details' : 'Show details'}
    </button>
    {open ? children : null}
  </section>;
}

Server execution

app/catalog/page.tsx
import Expandable from './Expandable';
export default async function Page() {
  const description = 'Prepared by the server before the interactive toggle.';
  return <main><h1>Catalogue</h1>
    <Expandable><p>{description}</p></Expandable>
  </main>;
}

PAUSE AND PREDICT

A server page imports a client button. The button imports a formatter. Which modules enter the button’s transitive client graph?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Server execution does not make returned data private

Any data deliberately passed to a client boundary or included in HTML is available to the browser. A private database record does not become safe merely because the query happened on the server. Define a minimal DTO containing only the fields the current viewer is permitted to receive. Authorization determines whether data may be read; serialization determines what leaves the server. Both need attention.

Props crossing the boundary must follow React serialization rules. Avoid the oversimplification that only JSON values are supported, but do not pass arbitrary class instances or closures as ordinary props. Server Function references have their own framework mechanism; they are not a general exception for every callback. If a browser widget needs a callback, usually define that callback inside the client module and pass plain domain data into it.

Audit dependency cost and data exposure independently

A small client bundle and a secure data boundary are related but separate goals. A dependency can be safe yet unnecessarily large. A tiny serialized prop can still contain a secret. Review imports to limit browser cost, then review returned fields to prevent exposure. The kata models only transitive import reachability and server-only violations, making those graph rules testable without pretending to compile a Next application.

In the real lab, inspect the server page, its interactive child and the browser network responses. Add a deliberate server-only import to a client component as an isolated experiment and confirm the build rejects it, then remove it. Search the produced response for a harmless sentinel placed only in private server data. Use a nonsecret test value; never prove safety by intentionally leaking a real credential.

PAUSE AND PREDICT

A Server Component queries a user record and passes the whole record to a client header. The header displays only displayName. Is the unused token field private?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Misconceptions to replace

Compare the tempting shortcut with the model you can verify in code.

CLAIM TO CHALLENGEAdding use client is a harmless universal fix for hook and import errors.
A more accurate model

It changes the dependency boundary and can increase browser code or expose invalid server dependencies. Move only the required interactive responsibility.

How to check it

N05 and N06 define client module boundaries; the graph kata detects transitive server-only imports.

CLAIM TO CHALLENGEServer Components can pass arbitrary closures as normal client props.
A more accurate model

Ordinary closures do not cross that boundary as arbitrary executable code. Define browser callbacks in client modules; Server Functions use a specific request mechanism.

How to check it

N05 and N19 explain boundary serialization and Server Function security responsibilities.

Mistakes to catch in your own code

  • A server query can still leak private fields through props or HTML.
  • Rendered children and module imports are different relationships.
  • Do not put use client at the root to make a hook error disappear without examining bundle and boundary effects.

Write it by hand

JavaScript logic playground

Audit the client import graph

Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.

  1. Implement solve({modules}). Each module has id, client, serverOnly and imports. Every imported ID exists and module IDs are unique.
  2. A module with client=true starts a client graph. Follow all transitive imports, including cycles. Return sorted clientIds and sorted violations containing reached serverOnly modules.
  3. Rendered children are intentionally absent from this graph. The exercise models dependency reachability, not the complete React compiler.

Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.

Ready when you are. Try the exercise before opening the worked solution.
Inspect 4 test cases
  1. Server parent stays outside client graph

    Input

    {
      "modules": [
        {
          "id": "page",
          "client": false,
          "serverOnly": false,
          "imports": [
            "button",
            "db"
          ]
        },
        {
          "id": "button",
          "client": true,
          "serverOnly": false,
          "imports": [
            "format"
          ]
        },
        {
          "id": "format",
          "client": false,
          "serverOnly": false,
          "imports": []
        },
        {
          "id": "db",
          "client": false,
          "serverOnly": true,
          "imports": []
        }
      ]
    }

    Expected

    {
      "clientIds": [
        "button",
        "format"
      ],
      "violations": []
    }
  2. Transitive privileged dependency

    Input

    {
      "modules": [
        {
          "id": "button",
          "client": true,
          "serverOnly": false,
          "imports": [
            "barrel"
          ]
        },
        {
          "id": "barrel",
          "client": false,
          "serverOnly": false,
          "imports": [
            "db"
          ]
        },
        {
          "id": "db",
          "client": false,
          "serverOnly": true,
          "imports": []
        }
      ]
    }

    Expected

    {
      "clientIds": [
        "barrel",
        "button",
        "db"
      ],
      "violations": [
        "db"
      ]
    }
  3. Cycle terminates

    Input

    {
      "modules": [
        {
          "id": "a",
          "client": true,
          "serverOnly": false,
          "imports": [
            "b"
          ]
        },
        {
          "id": "b",
          "client": false,
          "serverOnly": false,
          "imports": [
            "a"
          ]
        }
      ]
    }

    Expected

    {
      "clientIds": [
        "a",
        "b"
      ],
      "violations": []
    }
  4. No client entries

    Input

    {
      "modules": [
        {
          "id": "db",
          "client": false,
          "serverOnly": true,
          "imports": []
        }
      ]
    }

    Expected

    {
      "clientIds": [],
      "violations": []
    }
Reveal the worked solution and reasoning
solution.js
function solve(input) {
  const modules = new Map(input.modules.map(module => [module.id, module]));
  const seen = new Set();
  const pending = input.modules.filter(module => module.client).map(module => module.id);
  while (pending.length) {
    const id = pending.pop();
    if (seen.has(id)) continue;
    seen.add(id);
    for (const dependency of modules.get(id).imports) pending.push(dependency);
  }
  const clientIds = Array.from(seen).sort();
  const violations = clientIds.filter(id => modules.get(id).serverOnly);
  return { clientIds, violations };
}

The visited set makes traversal terminate on cycles and avoids repeated work for shared imports.

Following outgoing imports, not incoming parents, explains why a server page can import an interactive child without becoming a client module.

Verify it in a real Next.js application

Next.js application lab

Inspect a real import boundary and public DTO

Open the local application route /catalog after starting the workbench. Follow the experiment and collect the evidence described below.

Make the change

  1. Trace /catalog/keyboard through the server getCatalog helper to the client AddToCart control. Draw imported modules separately from the rendered component tree.
  2. Inspect the browser-facing product props. The cached catalogue returns only id, name, category, price and version; the session token and signing key are never product props.
  3. In an isolated copy, deliberately import the server-only catalogue or session helper into a Client Component. Run the build, record the boundary diagnostic and remove the violation.
  4. Rebuild the corrected application, inspect its network responses and confirm that a harmless private sentinel placed only in server code is absent from browser-visible data.

Check the behavior

  • The deliberate invalid import fails the build rather than exposing privileged code.
  • The restored project builds and its cart interaction works.
  • The public product payload contains only its documented fields.
  • The explanation distinguishes client module reachability from initial server rendering of Client Components.
Review the application reasoning

Never use a real credential as a sentinel. A server-only marker protects a module boundary; a deliberate DTO protects what that server code chooses to return.

The graph kata verifies reachability under a simplified model. The compiler and response inspection verify the actual framework boundary.

Open the project files and run instructions

A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.

The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.

Terminal
cd nextjs-interview-lab
npm ci
npm run dev

# In a second terminal
npm test

# Stop dev, then verify the production application
npm run build
npm start

# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2e

Open http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.

Explain it in an interview

Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.

  1. 01What exactly does use client affect?

    It establishes a client entry in the module dependency graph, so its imported dependencies must be client-compatible. It does not automatically move the importing Server Component into that graph. I trace imports rather than infer execution from the rendered DOM hierarchy.

    Follow-up questions

    • What happens to a shared utility?
    • Can a barrel import widen the boundary?
  2. 02Can a client wrapper contain server-rendered content?

    Yes, through composition such as a children prop constructed on the server. The wrapper does not need to import the privileged component implementation. Hiding those children on the client does not imply that their server work was deferred; I would inspect when the content was actually produced.

    Follow-up questions

    • Where should a context provider sit?
    • How would you defer expensive work until a later user action?
  3. 03Why use a DTO if the query runs on the server?

    Execution location does not control what data is sent afterward. Passing an entire record to a client component can expose fields the UI does not display. A DTO returns only the authorized fields required for the view, and the data-access layer performs the permission checks before producing it.

    Follow-up questions

    • Can hidden props be inspected by the browser?
    • Where should object ownership be verified?
  4. 04Can a Server Component pass any function to a Client Component?

    No. Ordinary closures cannot cross that boundary as arbitrary executable code. A client event callback should usually be defined in the client module. Server Functions use a specific reference and request mechanism, and each callable mutation still needs input validation and authorization.

    Follow-up questions

    • What can cross under React serialization rules?
    • Why is a Server Action still a public-facing boundary?

Check your understanding

Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.

FINAL KNOWLEDGE CHECK

A client accordion receives server-rendered children and initially hides them. What can you conclude about their server data work?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Your checkpoint

Mark what you can do independently

Loading your local progress.

Sources and further reading

© 2026 FrontendX. All rights reserved.