Next.js App Router: How to Draw the Server and Client Component Boundary

A team standard for the ‘use client’ boundary in the Next.js App Router, props that leak data, caching intent, authorization checks in Server Actions and measuring bundle size.
Technical summary
Technology
Next.js App Router, React Server Components, Server Actions, TypeScript
Topic
The server/client component boundary and data flow
Level
Intermediate–advanced
Prerequisites
  • Knowledge of React components and hooks
  • Basic Next.js project structure
  • TypeScript literacy
In this article7 sections

Most of the problems that come up in code reviews of Next.js App Router projects come from the same place: the 'use client' boundary has been put in the wrong place. The app works and the screens open; but the JavaScript sent to the client bloats, database queries move to the browser and a customer’s internal notes become visible in network traffic. This guide ties the Server and Client Component distinction, caching intent and Server Actions security into a single team standard for teams developing corporate business applications.

The model the App Router brings

In the Pages Router, a page was rendered on the server as a whole and hydrated in the browser; data came through page-level functions such as getServerSideProps or getStaticProps. The App Router (the app/ directory) brings this model down to the component level: every component under app/ is a React Server Component by default. The component can be asynchronous, can go directly to the data source, and its output goes to the browser not as JavaScript but as a serialized render result (the RSC payload).

File conventions are part of this model: layout.tsx defines the persistent shell, page.tsx the route’s content, loading.tsx the Suspense fallback, error.tsx the error boundary and route.ts an HTTP endpoint. error.tsx, however, has to be a Client Component. You meet the boundary in the very first file. The effect of rendering strategies on search engine visibility is a separate topic; we explained it in the React, SSR, SSG and technical SEO article. Here the focus is component architecture.

The difference between Server and Client Components

The two component types use the same JSX syntax, but their capabilities are almost the opposite of each other. This table is an adequate starting point for deciding:

Needs Server Component Client Component
Database, internal API, file system access Suitable Not suitable
Secret keys, tokens, connection strings Suitable Never
useState, useEffect, event handlers Unusable Suitable
window, localStorage, browser APIs Unusable Suitable
Large formatting/markdown library Preferred (doesn’t go into the bundle) Increases bundle size
Context provider (theme, query client) Not directly Required

The point most often confused in the field is this: a Client Component is also rendered to HTML on the server on the first request, then hydrated in the browser. The “client” label doesn’t mean “runs only in the browser”; it means “its code is also sent to the browser”. That’s why window or localStorage access in a Client Component must be done inside useEffect. If it isn’t, you get an error in the server render or a hydration mismatch.

Where to put the ‘use client’ boundary

The 'use client' directive marks not a component but a module boundary. The file containing the directive and every module this file imports go into the client bundle. The rule is simple: put the directive as close to the leaves of the tree as possible.

The structure we recommend for a typical order list screen in corporate web applications:

app/
  (panel)/
    orders/
      page.tsx            // Server: fetches data, renders the table
      loading.tsx         // Server: skeleton view
      actions.ts          // 'use server': mutations
      _components/
        OrdersTable.tsx      // Server: produces the rows
        StatusFilter.tsx     // 'use client': select + router
        ApproveButton.tsx    // 'use client': useActionState
lib/
  db.ts                   // import 'server-only'
  order-service.ts        // import 'server-only'

Most boundary errors are prevented with these three rules:

  • A Server Component can import a Client Component; the reverse isn’t possible. If a server component is needed inside a Client Component, pass it in from outside as children or another prop. With this “hole-punching” pattern, the content of a client-side dropdown panel stays rendered on the server.
  • Props crossing the boundary must be serializable. Plain objects, arrays, strings, numbers and Date can cross; class instances and ordinary functions can’t. If you need to pass a function, it must be a Server Action.
  • Lock down server-only modules. If a module that imports the server-only package accidentally enters a Client Component chain, the build fails. This should be the first line of every file in the data access layer.
// lib/order-service.ts
import 'server-only';
import { db } from './db';

export async function getOrders(companyId: string) {
  return db.order.findMany({
    where: { companyId },
    select: { id: true, number: true, status: true, amount: true },
  });
}

The select in the example isn’t a coincidence. Every prop passed from a Server Component to a Client Component reaches the browser inside the RSC payload. If you give the whole user record to a client component, the password hash, internal notes or cost fields can be read in the network tab even if they aren’t shown on screen. Not being visible on screen isn’t the same as being secret. The same logic applies to environment variables: only variables with the NEXT_PUBLIC_ prefix are embedded in the client bundle; never give this prefix to secret values.

Data fetching and caching behavior

In the App Router, data is fetched with await inside the Server Component that uses it. If several components need the same data in the same render, a data function wrapped with React’s cache function cuts duplicate queries per request. Start independent calls in parallel with Promise.all; a chain of sequential awaits produces waterfall latency and is the classic cause of slow pages.

Caching is the part of the App Router that has changed the most between versions. In Next.js 14, fetch calls were cached by default; with Next.js 15 the default became not caching; newer versions brought an opt-in cache component model and the 'use cache' directive. Such a shifting default can’t be relied on. As a team standard, write the intent explicitly on every call:

Intent App Router equivalent
Fresh data on every request fetch(url, { cache: 'no-store' })
Data refreshed at a set interval fetch(url, { next: { revalidate: 300 } })
Event-triggered revalidation next: { tags: ['products'] } + revalidateTag('products') (in Next.js 16 a cache profile is expected as the second argument, e.g. 'max')
Dynamic rendering at route level export const dynamic = 'force-dynamic'
Path-based revalidation revalidatePath('/orders')

In corporate business applications, the real risk is user- or company-specific data landing in a shared cache. A route that reads cookies() or headers() is rendered dynamically; but if you forget to put the tenant/company ID in the cache key when wrapping data fetched with an ORM in unstable_cache or a similar mechanism, one company’s data can be shown to another company. This isn’t a performance bug, it’s a data leak. For every change that caches permission-dependent data, separately check in code review that the key includes the identity information. In Next.js 15 and later, cookies(), headers() and page params are asynchronous, so they must be read with await.

Form handling with Server Actions

A Server Action is an asynchronous server function marked with the 'use server' directive that can be called from the client. When given to the action prop of a <form> element, it works even before JavaScript loads (progressive enhancement) and removes the need to write a separate API route for most internal forms.

// app/(panel)/orders/actions.ts
'use server';
import { z } from 'zod';
import { revalidatePath } from 'next/cache';
import { getSession } from '@/lib/auth';
import { approveOrder } from '@/lib/order-service';

const Input = z.object({ orderId: z.string().uuid() });

export async function approve(_prev: unknown, formData: FormData) {
  const session = await getSession();
  if (!session || !session.roles.includes('Approver')) {
    return { error: 'You are not authorized for this action.' };
  }
  const result = Input.safeParse({ orderId: formData.get('orderId') });
  if (!result.success) return { error: 'Invalid request.' };

  await approveOrder(result.data.orderId, session.userId);
  revalidatePath('/orders');
  return { error: null };
}

On the client side, React 19’s useActionState hook manages the action’s return value and pending state; useFormStatus from react-dom disables the button inside the form during submission. The useFormState you see in older examples has been replaced by useActionState.

The most overlooked property of Server Actions is this: at build time an ID is generated for each action, and the action behaves like an endpoint that accepts POST requests with this ID. In other words, it’s exposed. Showing the button only to authorized users isn’t a security check; someone can send the request by hand. Authorization and input validation are done inside the action, as in the example. The validation in web forms article explains in detail how to set up validation with the same schema on client and server.

Common mistakes and bundle size control

Mistakes we come across again and again in code reviews, and their fixes:

  • Adding 'use client' to the root layout: Usually done for a theme or query provider, and it turns the whole app into a client component. The right way: move the provider into a separate Providers.tsx Client Component and wrap {children} in it in the layout. The children are still rendered on the server.
  • Date and locale mismatch: If the server’s time zone differs from the browser’s, new Date().toLocaleString() produces a hydration warning. Format dates on the server with a fixed time zone (Intl.DateTimeFormat + timeZone: 'Europe/Istanbul').
  • Moving data fetching to the client unnecessarily: Fetching the initial view’s data with useEffect means an empty screen, a loading indicator and an extra round trip. Let the initial data come from the server; keep client-side data libraries for data that’s updated later and depends on interaction. The state management in React article covers this distinction.
  • Importing a heavy library on the client: Use next/dynamic to load components such as charts, rich text editors or PDF viewers only when needed.
  • Making the whole page wait for one slow query: Wrap the slow section in <Suspense>; the rest of the page arrives immediately via streaming.

You can’t control a bundle you don’t measure. Since the size information in the next build output changes from version to version (per-route size columns were removed in newer versions), tie measurement to an analysis tool. In projects built with Webpack, the @next/bundle-analyzer plugin does the job; in versions building with Turbopack, look at the bundle analysis option in the documentation for the version you use:

npm i -D @next/bundle-analyzer

// next.config.mjs
import bundleAnalyzer from '@next/bundle-analyzer';
const withBundleAnalyzer = bundleAnalyzer({ enabled: process.env.ANALYZE === 'true' });
export default withBundleAnalyzer({});

// run
ANALYZE=true npm run build

To keep the boundary from degrading over time, write these checks into the team standard:

  • Data access and secret configuration modules start with import 'server-only'.
  • For every file containing 'use client', the question “why client?” is answered in code review.
  • Client Components receive only the fields the screen needs, not the full data model.
  • Every Server Action does its own session, authorization and input validation.
  • The caching intent (fresh, timed, tagged) is written explicitly on every data call.
  • The JavaScript size per route in the bundle analysis report is compared between releases.

If it isn’t yet clear whether the App Router is the right tool for your project, first look at the WordPress or Next.js comparison. When moving an existing app to this architecture or designing a new internal system, we can plan component boundaries and the caching strategy together within the scope of our React and Next.js web applications service. For API details, the official Next.js App Router documentation and React’s Server Components reference page should be the reference.

Frequently asked questions

Why is marking an entire page with ‘use client’ a problem?

The directive causes the file and all the modules it imports to go into the client bundle. Data fetching moves to the browser, libraries that could stay on the server get downloaded, and the risk of secret configuration leaking into client code increases. Split the interactive part into a small separate component and mark only that.

Can useState or useEffect be used in a Server Component?

No. A Server Component is rendered only on the server (at request time or build time); its code never runs in the browser. Anything that requires state, effects or browser APIs belongs to a Client Component. The Server Component fetches the data and passes the result as props to an interactive Client Component.

Does a Server Action replace an API endpoint?

For the app’s own forms and mutations, often yes. For a mobile client, integrations or third-party consumers, however, a versionable HTTP API (a Route Handler or a separate service) is still needed. Since Server Actions behave like publicly exposed POST endpoints, input validation and authorization checks must be done separately inside every action.

Why does caching behavior seem to differ from version to version?

Next.js changed the App Router’s default caching behavior in major versions; for example, with Next.js 15, fetch requests stopped being cached by default, and later versions added new opt-in caching models. Go by the documentation for the version in your project, and write the caching intent explicitly on every data call.

Support

Contact us for support or a discovery session on this topic.

Contact form
[email protected]

Eretek Web

We build and maintain corporate websites, WordPress and CMS platforms, intranet and SharePoint portals, document management, and form and approval workflows, and keep them secure and up to date.

Knowledge Center

Other articles