Bird
Raised Fist0
NextJSframework~15 mins

Server-only modules in NextJS - Deep Dive

Choose your learning style10 modes available
Overview - Server-only modules
What is it?
Server-only modules in Next.js are JavaScript or TypeScript files that run only on the server side. They contain code that should never be sent to the browser, such as database queries, secret keys, or server logic. These modules help keep sensitive operations secure and improve performance by separating server tasks from client tasks.
Why it matters
Without server-only modules, sensitive code like database credentials or API keys could accidentally be exposed to users, causing security risks. Also, mixing server and client code can make apps slower and harder to maintain. Server-only modules solve these problems by clearly separating what runs on the server from what runs in the browser.
Where it fits
Before learning server-only modules, you should understand basic Next.js app structure and the difference between server and client environments. After mastering server-only modules, you can explore advanced server features like API routes, server components, and server actions.
Mental Model
Core Idea
Server-only modules are special files that run exclusively on the server to keep sensitive code safe and separate from browser code.
Think of it like...
It's like having a locked office where you keep important documents (server-only modules) that no visitor (browser) can enter, while the reception area (client code) is open to everyone.
┌───────────────┐       ┌───────────────┐
│ Client Code   │──────▶│ Browser       │
│ (public)      │       │ (user device) │
└───────────────┘       └───────────────┘
        ▲                      ▲
        │                      │
        │                      │
┌───────────────┐       ┌───────────────┐
│ Server-only   │──────▶│ Server        │
│ Modules       │       │ (secure code) │
└───────────────┘       └───────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding server vs client code
🤔
Concept: Learn the basic difference between code that runs on the server and code that runs in the browser.
In Next.js, some code runs on the server (like fetching data from a database), and some runs in the browser (like showing buttons or animations). Server code can access secrets and files on the server, but client code cannot. Knowing this helps you decide where to put your code.
Result
You can identify which parts of your app run on the server and which run on the client.
Understanding this split is the foundation for writing secure and efficient Next.js apps.
2
FoundationWhat are server-only modules?
🤔
Concept: Introduce server-only modules as files that run only on the server and never reach the browser.
Server-only modules are files you create in your Next.js app that contain code meant only for the server. For example, a module that connects to your database or reads secret environment variables. Next.js ensures these modules are never bundled into the client-side code.
Result
You know how to create modules that keep sensitive code safe on the server.
Knowing how to isolate server code prevents accidental leaks of secrets to users.
3
IntermediateHow to create server-only modules
🤔Before reading on: Do you think server-only modules require special file extensions or folder locations? Commit to your answer.
Concept: Learn the practical ways to mark modules as server-only in Next.js.
In Next.js, you can create server-only modules by placing them outside the 'app' or 'pages' directories or by using the 'use server' directive at the top of the file. Also, importing server-only modules inside client components will cause errors, enforcing separation.
Result
You can write modules that Next.js treats as server-only and avoid importing them in client code.
Understanding how Next.js enforces server-only modules helps prevent accidental client exposure.
4
IntermediateUsing server-only modules in server components
🤔Before reading on: Can server-only modules be imported into client components without errors? Commit to your answer.
Concept: Learn how server components can safely import server-only modules to run secure logic.
Server components in Next.js run only on the server and can import server-only modules freely. This allows you to fetch data, access secrets, or perform backend logic inside server components without exposing it to the client.
Result
You can build server components that use server-only modules to keep logic secure and efficient.
Knowing this pattern lets you build apps that are both secure and fast by leveraging server components.
5
AdvancedCommon errors with server-only modules
🤔Before reading on: What happens if you import a server-only module inside a client component? Predict the error or behavior.
Concept: Understand the errors and pitfalls when mixing server-only modules with client code.
If you try to import a server-only module inside a client component, Next.js will throw a build error because it cannot include server-only code in the browser bundle. This helps catch mistakes early. You must keep server-only imports inside server components or API routes.
Result
You learn to avoid common mistakes that cause build failures and security risks.
Recognizing these errors helps maintain the clear boundary between server and client code.
6
ExpertServer-only modules and server actions integration
🤔Before reading on: Do you think server actions can import server-only modules directly? Commit to your answer.
Concept: Explore how server-only modules work with server actions to handle secure user interactions.
Server actions are special functions that run on the server triggered by client events. They can import server-only modules to perform secure tasks like database writes or authentication. This integration allows you to write clean, secure, and efficient server logic triggered by the client without exposing sensitive code.
Result
You can build interactive features that keep secrets safe and run securely on the server.
Understanding this integration unlocks powerful patterns for secure full-stack Next.js apps.
Under the Hood
Next.js uses its build system to analyze imports and code usage. When it detects a module marked as server-only or containing the 'use server' directive, it excludes that module from the client-side bundle. Server-only modules run in the Node.js environment on the server, where they can access environment variables, file systems, and databases. The client bundle only includes code safe for browsers, ensuring no server-only code leaks.
Why designed this way?
This design prevents accidental exposure of sensitive code to users, a common security risk in web apps. It also optimizes performance by sending only necessary code to the browser. Alternatives like bundling everything together risk leaking secrets or bloating client code. Next.js's approach enforces clear boundaries and improves developer experience by catching mistakes at build time.
┌─────────────────────────────┐
│       Next.js Build         │
├──────────────┬──────────────┤
│              │              │
│  Server-only │  Client-side │
│  Modules     │  Code        │
│  (Node.js)   │  (Browser)   │
│              │              │
│  - Access    │  - UI Logic  │
│    secrets   │  - Events    │
│  - DB calls  │  - Rendering │
└──────────────┴──────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Can server-only modules be safely imported into client components? Commit to yes or no.
Common Belief:You can import server-only modules anywhere, including client components, without issues.
Tap to reveal reality
Reality:Importing server-only modules in client components causes build errors because the code cannot run in the browser.
Why it matters:Ignoring this causes your app to fail building and can expose sensitive code if bypassed.
Quick: Do server-only modules run on the client if imported indirectly? Commit to yes or no.
Common Belief:If a server-only module is imported by another module used in the client, it will run in the browser.
Tap to reveal reality
Reality:Next.js prevents server-only modules from being bundled into client code, even if imported indirectly.
Why it matters:This prevents accidental leaks of server code and secrets to the browser.
Quick: Are server-only modules just a naming convention with no real effect? Commit to yes or no.
Common Belief:Server-only modules are only a developer naming convention and do not affect bundling or security.
Tap to reveal reality
Reality:Next.js enforces server-only modules at build time, excluding them from client bundles and throwing errors if misused.
Why it matters:Relying on naming alone risks security and build failures.
Quick: Can server-only modules access browser APIs like 'window' or 'document'? Commit to yes or no.
Common Belief:Server-only modules can use browser APIs because they run in the same environment as client code.
Tap to reveal reality
Reality:Server-only modules run in Node.js on the server and cannot access browser APIs like 'window' or 'document'.
Why it matters:Using browser APIs in server-only modules causes runtime errors and confusion.
Expert Zone
1
Server-only modules can be nested deeply and imported by multiple server components without duplication in the client bundle.
2
Using the 'use server' directive inside a module signals Next.js to treat all exports as server-only, even if the file is in a shared folder.
3
Server-only modules can leverage Node.js APIs directly, enabling powerful backend logic without extra configuration.
When NOT to use
Avoid server-only modules when code must run in both client and server environments, such as UI logic or shared utilities. Instead, use universal modules that do not rely on server-only features. For client-only code, use client components and hooks. For API endpoints, use Next.js API routes rather than server-only modules.
Production Patterns
In production, server-only modules commonly hold database clients, authentication logic, and secret management. They are imported by server components or server actions to keep sensitive operations secure. Teams often organize server-only code in dedicated folders and use strict linting rules to prevent accidental client imports.
Connections
Server Components
Server-only modules are often imported by server components to run secure logic.
Understanding server-only modules clarifies how server components keep sensitive code off the client.
API Routes
Both server-only modules and API routes run on the server and handle backend logic securely.
Knowing server-only modules helps you write cleaner API routes by separating concerns.
Operating System Permissions
Server-only modules rely on server environment permissions to access files and secrets safely.
Understanding OS permissions helps grasp why server-only modules can access sensitive resources unavailable to browsers.
Common Pitfalls
#1Importing server-only modules inside client components causing build errors.
Wrong approach:import db from '../server/db'; export default function ClientComponent() { // Using server-only db in client component return
{db.getData()}
; }
Correct approach:import DataDisplay from './DataDisplay.server'; export default function ClientComponent() { return ; } // DataDisplay.server.js imports server-only modules safely
Root cause:Misunderstanding that client components cannot include server-only code.
#2Placing server-only modules in shared folders without 'use server' directive, causing accidental client bundling.
Wrong approach:// utils/db.js export function query() { /* server code */ } // imported by client component import { query } from '../utils/db';
Correct approach:// utils/db.js 'use server'; export function query() { /* server code */ } // prevents client bundling errors
Root cause:Not marking shared modules explicitly as server-only.
#3Using browser-only APIs inside server-only modules causing runtime errors.
Wrong approach:export function getData() { console.log(window.location.href); return 'data'; }
Correct approach:export function getData() { // Server-side logic without browser APIs return 'data'; }
Root cause:Confusing server environment with browser environment.
Key Takeaways
Server-only modules keep sensitive code safe by running exclusively on the server in Next.js.
Next.js enforces server-only modules by excluding them from client bundles and throwing errors if misused.
Server components can import server-only modules freely to perform secure backend logic.
Mixing server-only modules with client code causes build errors and security risks.
Understanding server-only modules is essential for building secure, efficient full-stack Next.js applications.

Practice

(1/5)
1. What is the main purpose of server-only modules in Next.js?
easy
A. To enable server code to be bundled with client JavaScript
B. To run code on both server and client for faster rendering
C. To allow client-side code to access server secrets directly
D. To run code only on the server and keep it hidden from the browser

Solution

  1. Step 1: Understand server-only module purpose

    Server-only modules run exclusively on the server and are not sent to the browser.
  2. Step 2: Identify security benefit

    This keeps secrets safe and improves app security by hiding sensitive code from clients.
  3. Final Answer:

    To run code only on the server and keep it hidden from the browser -> Option D
  4. Quick Check:

    Server-only modules hide code from browser = A [OK]
Hint: Server-only means code runs only on server, hidden from browser [OK]
Common Mistakes:
  • Thinking server-only modules run on client too
  • Assuming server-only modules expose secrets to browser
  • Confusing server-only with shared server-client code
2. Which line correctly marks a Next.js module as server-only?
easy
A. export const client = true;
B. export const runtime = 'edge';
C. import 'server-only';
D. export default function ServerOnly() {}

Solution

  1. Step 1: Recall server-only marking syntax

    Next.js uses import 'server-only'; to mark server-only modules.
  2. Step 2: Compare options

    import 'server-only'; matches the correct syntax; others either mark edge runtime or client code.
  3. Final Answer:

    import 'server-only'; -> Option C
  4. Quick Check:

    Server-only marker = import 'server-only' [OK]
Hint: Look for import 'server-only' to mark server-only [OK]
Common Mistakes:
  • Using 'edge' runtime which is for edge functions, not server-only
  • Confusing client export with server-only marking
  • Missing the import keyword
3. Given this server-only module code in Next.js, what will happen if you try to import it in a client component?
import 'server-only';

export function secretData() {
  return 'top-secret';
}
medium
A. The client component will fail to compile with an error
B. The client component will receive the secret data as a string
C. The secretData function will run on the client without errors
D. The secretData function will be bundled into client JavaScript

Solution

  1. Step 1: Understand server-only import restrictions

    Server-only modules cannot be imported into client components; Next.js blocks this to protect secrets.
  2. Step 2: Predict behavior on import

    Trying to import causes a compile-time error because the module is not allowed in client code.
  3. Final Answer:

    The client component will fail to compile with an error -> Option A
  4. Quick Check:

    Importing server-only in client causes error = D [OK]
Hint: Server-only modules cannot be imported by client components [OK]
Common Mistakes:
  • Assuming server-only code runs on client
  • Thinking secret data is exposed to client
  • Believing server-only modules are bundled with client code
4. You wrote this server-only module but get an error when running your Next.js app:
export function getSecret() {
  return 'hidden';
}

What is missing to make this module server-only?
medium
A. You need to add import 'server-only'; at the top
B. You must rename the function to start with 'server'
C. You should import React in this module
D. You need to export the function as default

Solution

  1. Step 1: Identify server-only module requirement

    Next.js requires import 'server-only'; to mark a module as server-only.
  2. Step 2: Check given code

    The code lacks this import, so Next.js treats it as shared or client code, causing errors if used improperly.
  3. Final Answer:

    You need to add import 'server-only'; at the top -> Option A
  4. Quick Check:

    Missing 'server-only' import causes error = A [OK]
Hint: Always add import 'server-only'; to mark server-only [OK]
Common Mistakes:
  • Thinking function name controls server-only status
  • Assuming React import is needed for server-only modules
  • Believing default export affects server-only behavior
5. You want to fetch a secret API key only on the server in Next.js and prevent it from being sent to the client. Which approach correctly uses server-only modules to achieve this?
// secret.js
import 'server-only';
export function getApiKey() {
  return process.env.API_KEY;
}

// page.jsx
'use client';
import { getApiKey } from './secret';

export default function Page() {
  const key = getApiKey();
  return <p>API Key: {key}</p>;
}
hard
A. This code will cause an error because getApiKey is called in a client component
B. You should move getApiKey call inside a server component or server action
C. This code works and safely shows the API key on the client
D. You must export getApiKey as default to work

Solution

  1. Step 1: Understand server-only module usage

    Server-only modules cannot be imported or called directly in client components without error.
  2. Step 2: Analyze the code

    The page.jsx is a client component calling getApiKey(), which is server-only, causing an error.
  3. Step 3: Correct approach

    Call getApiKey() inside a server component or server action to keep the secret on the server.
  4. Final Answer:

    You should move getApiKey call inside a server component or server action -> Option B
  5. Quick Check:

    Server-only calls must be inside server components = B [OK]
Hint: Call server-only functions only inside server components or actions [OK]
Common Mistakes:
  • Calling server-only functions directly in client components
  • Exposing secrets by rendering them in client JSX
  • Assuming default export fixes server-only usage
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard