0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · 课时

使用 server-only 与 client-only 划分模块边界

使用隔离包,防止服务器机密和沉重代码泄漏到客户端包中。

使用 server-only 与 client-only 划分模块边界 是 CoddyKit 上的免费 Next.js 15 Fullstack (App Router + Server Actions) 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack (App Router + Server Actions) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Module Boundaries Matter

Next.js 15 runs JavaScript in two distinct environments: the Node.js server and the browser client. Code you write in app/ can silently end up in either bundle depending on how it is imported.

Without explicit boundaries, a single careless import chain can expose:

  • Database credentials and API keys stored in environment variables
  • Server-only business logic that should never reach users
  • Heavy Node.js libraries (crypto, fs, net) that inflate the client bundle

The poison-pill packages server-only and client-only are the idiomatic Next.js solution. They throw a build-time error the moment a module crosses the wrong boundary — catching the mistake before any code ships to production.

Installing the Packages

Both packages are published by the Next.js team and carry zero runtime code. Their entire purpose is to act as a sentinel import that the bundler recognises.

Install them once in your project:

npm install server-only client-only

They are tiny — each package contains only a single index.js that throws an error if evaluated in the wrong environment. The build pipeline (via React's bundler conditions) ensures the error fires at compile time, not at runtime.

You do not need to configure anything in next.config.ts. The packages rely on the react-server export condition that Next.js sets automatically.

Marking a Module as Server-Only

Any file that reads server-side secrets, talks to a database, or uses Node.js built-ins should begin with a single import:

import 'server-only'

If a Client Component (or any client-side code) ever imports this module, Next.js will abort the build with a clear error message pointing to the offending import. The example below shows a data-access layer that must never reach the browser.

// lib/db.ts
import 'server-only'
import { Pool } from 'pg'

const pool = new Pool({
  connectionString: process.env.DATABASE_URL, // secret — server only
})

export async function getUserById(id: string) {
  const { rows } = await pool.query(
    'SELECT id, name, email FROM users WHERE id = $1',
    [id]
  )
  return rows[0] ?? null
}

What Happens When the Boundary Is Violated

Suppose a developer mistakenly imports the server-only data-access layer into a Client Component. Without the poison pill the secret DATABASE_URL would silently appear in the browser bundle.

With server-only in place, the Next.js build immediately stops and prints:

Error: This module cannot be imported from a Client Component module.
It should only be used from a Server Component.

This makes the violation impossible to ship accidentally. The error is deterministic — it fires on every next build and next dev hot-reload that crosses the boundary.

// app/dashboard/page.tsx — Server Component, safe to import lib/db
import { getUserById } from '@/lib/db'

export default async function DashboardPage() {
  const user = await getUserById('user_123')
  return <h1>Welcome, {user?.name}</h1>
}

// app/components/ProfileCard.tsx — Client Component
'use client'
// import { getUserById } from '@/lib/db'  // ← BUILD ERROR if uncommented
export function ProfileCard({ name }: { name: string }) {
  return <p>{name}</p>
}

Marking a Module as Client-Only

client-only solves the opposite problem. Some modules depend on browser-exclusive APIs like window, document, localStorage, or browser-specific third-party SDKs.

If such a module is imported into a Server Component, Node.js will throw at runtime because those browser globals do not exist on the server. client-only converts that runtime surprise into a build-time error.

Add the import at the top of any browser-exclusive utility:

import 'client-only'

// lib/analytics.ts
import 'client-only'

// This module calls browser APIs — it must never run on the server
export function trackEvent(name: string, props?: Record<string, unknown>) {
  if (typeof window === 'undefined') return // extra guard, but poison-pill fires first
  window.gtag?.('event', name, props)
}

export function getStoredUserId(): string | null {
  return localStorage.getItem('userId')
}

Safe Pattern: Server Data Passed as Props

The canonical Next.js 15 pattern is to fetch data in a Server Component using a server-only module, then pass safe, serialisable values down to Client Components as props.

No secrets, no database handles, no Node.js-only objects ever cross the network boundary — only plain data that can be safely serialised to JSON.

// lib/user-service.ts
import 'server-only'
import { pool } from './db'

export interface UserProfile {
  id: string
  name: string
  avatarUrl: string
}

export async function getProfile(userId: string): Promise<UserProfile | null> {
  const { rows } = await pool.query(
    'SELECT id, name, avatar_url FROM users WHERE id = $1',
    [userId]
  )
  if (!rows[0]) return null
  return { id: rows[0].id, name: rows[0].name, avatarUrl: rows[0].avatar_url }
}

// app/profile/page.tsx — Server Component
import { getProfile } from '@/lib/user-service'
import { AvatarCard } from '@/components/AvatarCard' // 'use client'

export default async function ProfilePage({ params }: { params: { id: string } }) {
  const profile = await getProfile(params.id)
  if (!profile) return <p>Not found</p>
  // Only serialisable data crosses to the client
  return <AvatarCard name={profile.name} avatarUrl={profile.avatarUrl} />
}

Server Actions Are Not a Bypass

Server Actions are functions that run on the server but are called from client-side code. A common misconception is that marking a function with 'use server' automatically protects the entire module.

It does not. The 'use server' directive only tells Next.js to expose that function as an HTTP endpoint. Other exports in the same file could still leak if imported directly.

Best practice: keep Server Actions in dedicated actions/ files and still guard shared server utilities with server-only.

// app/actions/update-profile.ts
'use server'
import { getUserById } from '@/lib/db' // lib/db has 'server-only' — safe
import { revalidatePath } from 'next/cache'

export async function updateProfileAction(formData: FormData) {
  const name = formData.get('name') as string
  const userId = formData.get('userId') as string

  // Business logic runs entirely on the server
  const existing = await getUserById(userId)
  if (!existing) throw new Error('User not found')

  // db update omitted for brevity
  revalidatePath('/profile')
}

// app/profile/edit/page.tsx — this is a Client Component form
'use client'
import { updateProfileAction } from '@/app/actions/update-profile'

export function EditForm({ userId }: { userId: string }) {
  return (
    <form action={updateProfileAction}>
      <input type="hidden" name="userId" value={userId} />
      <input name="name" placeholder="New name" />
      <button type="submit">Save</button>
    </form>
  )
}

Organising Your lib/ Folder by Boundary

A predictable folder convention eliminates guesswork about which environment a utility targets. A widely-adopted layout looks like this:

  • lib/server/ — every file starts with import 'server-only'
  • lib/client/ — every file starts with import 'client-only'
  • lib/shared/ — pure functions with no environment-specific imports (safe in both)

With this structure, a code reviewer can immediately tell whether a new utility is correctly placed before even reading its contents. CI linting rules can also enforce that files inside lib/server/ contain the sentinel import.

// lib/shared/format.ts — no sentinel needed, works anywhere
export function formatCurrency(amount: number, currency = 'USD'): string {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(amount)
}

// lib/server/stripe.ts
import 'server-only'
import Stripe from 'stripe'

export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: '2024-11-20.acacia',
})

// lib/client/toast.ts
import 'client-only'
import { toast } from 'sonner'

export function showSuccess(msg: string) {
  toast.success(msg)
}

Combining with TypeScript Path Aliases

TypeScript path aliases in tsconfig.json make boundary-aware imports ergonomic and consistent across the codebase. You can encode the boundary directly in the alias name, making imports self-documenting.

// tsconfig.json (relevant excerpt)
// {
//   "compilerOptions": {
//     "paths": {
//       "@server/*": ["./lib/server/*"],
//       "@client/*": ["./lib/client/*"],
//       "@shared/*": ["./lib/shared/*"]
//     }
//   }
// }

// Usage in a Server Component:
import { stripe } from '@server/stripe'
import { formatCurrency } from '@shared/format'

// Usage in a Client Component:
import { showSuccess } from '@client/toast'
import { formatCurrency } from '@shared/format'

// Attempting to import @server/* in a Client Component
// triggers the server-only build error immediately.

Third-Party Packages Without Directives

Many npm packages (especially older ones) include no 'use client' or 'use server' directive. The Next.js bundler applies a heuristic: if a package has no directive it is treated as shared — eligible for both environments.

This can be a problem when a package uses browser globals internally. The solution is to wrap it in your own lib/client/ module marked with client-only, so the import chain is explicit and auditable.

// lib/client/chart-wrapper.ts
import 'client-only'
// chart.js has no 'use client' directive but uses window internally
import { Chart, registerables } from 'chart.js'

Chart.register(...registerables)

export { Chart }
export type { ChartConfiguration } from 'chart.js'

// components/RevenueChart.tsx
'use client'
import { Chart } from '@client/chart-wrapper' // boundary enforced
import { useEffect, useRef } from 'react'

export function RevenueChart({ data }: { data: number[] }) {
  const ref = useRef<HTMLCanvasElement>(null)
  useEffect(() => {
    if (!ref.current) return
    const ctx = ref.current.getContext('2d')!
    new Chart(ctx, { type: 'line', data: { labels: data.map(String), datasets: [{ data }] } })
  }, [data])
  return <canvas ref={ref} />
}

Verifying Your Bundles with @next/bundle-analyzer

Poison-pill packages prevent accidental leakage at build time, but it is still valuable to verify your bundles visually. The @next/bundle-analyzer package generates an interactive treemap of every module in each bundle.

Use it to confirm that server-only modules (database clients, Stripe SDKs, heavy Node.js libs) are absent from the client chunk and vice versa. If a secret-containing module appears in the client bundle despite the sentinel import, it usually means a dynamic import or a re-export bypassed the check.

// next.config.ts
import type { NextConfig } from 'next'
import withBundleAnalyzer from '@next/bundle-analyzer'

const withAnalyzer = withBundleAnalyzer({
  enabled: process.env.ANALYZE === 'true',
})

const nextConfig: NextConfig = {
  // your existing config
}

export default withAnalyzer(nextConfig)

// Run analysis:
// ANALYZE=true next build
// Opens two browser tabs:
//   - client.html  (browser bundle — check for leaked server deps)
//   - server.html  (server bundle)

Knowledge Check: server-only vs client-only

Choose the best answer to the question below.

Recap: Module Boundaries with server-only and client-only

In this lesson you learned how to enforce hard module boundaries in a Next.js 15 application:

  • import 'server-only' — turns a module into a build-time error if imported from any client-side code. Use it on database clients, secret-reading utilities, and Node.js-exclusive code.
  • import 'client-only' — mirrors the pattern for browser-exclusive modules, catching server-side imports before they cause runtime crashes.
  • The safe data-flow pattern: fetch in a Server Component using server-only utilities, then pass serialisable props to Client Components — no secrets, no Node APIs cross the wire.
  • Organise lib/ into server/, client/, and shared/ sub-directories, and align TypeScript path aliases to make boundaries self-documenting.
  • Wrap third-party packages that lack directives inside your own boundary-marked modules to keep the import graph auditable.
  • Combine poison-pill packages with @next/bundle-analyzer to visually verify that no server-only dependencies appear in client chunks.

These two packages cost almost nothing to add and eliminate an entire class of security and performance bugs before they ever reach production.

常见问题解答

「使用 server-only 与 client-only 划分模块边界」课时是免费的吗?

是的 — 「使用 server-only 与 client-only 划分模块边界」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack (App Router + Server Actions) 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。

「使用 server-only 与 client-only 划分模块边界」这节课中我会学到什么?

使用隔离包,防止服务器机密和沉重代码泄漏到客户端包中。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack (App Router + Server Actions),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Next.js 15 Fullstack (App Router + Server Actions) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack (App Router + Server Actions) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「使用 server-only 与 client-only 划分模块边界」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Next.js 15 Fullstack (App Router + Server Actions) 课中编写并运行代码吗?

能。每节 Next.js 15 Fullstack (App Router + Server Actions) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 分析并缩小客户端包
  2. Turbopack 与编译器配置深入解析
  3. 使用 server-only 与 client-only 划分模块边界
  4. 动态导入、代码拆分与延迟水合
← 返回 Next.js 15 Fullstack (App Router + Server Actions)