Claude
Skills
Sign in
Back

nextjs-static-shells

Included with Lifetime
$97 forever

Static-first Next.js 16 architecture patterns: cached shells with dynamic slots, provider islands, 'use cache' boundaries, and link preloading strategy. Use when building or refactoring Next.js routes to maximize static rendering, implementing 'use cache' with dynamic personalization, splitting entry vs static renderers, scoping client providers, or tuning prefetch behavior. Triggers on 'static shell', 'use cache pattern', 'dynamic slots', 'provider island', 'prefetch strategy', 'static first', 'cache boundary', 'route goes dynamic unexpectedly', or any Next.js architecture work involving mixed static/dynamic rendering.

Web Devnextjsarchitecturecachingperformancerscstaticassets

What this skill does


# Static-First Next.js 16 Patterns

Build a **static shell first**, then cut **small dynamic holes** where personalization or request-specific behavior is required.

- Static shell = deterministic, cacheable, fast first paint
- Dynamic holes = isolated request/user behavior streamed with Suspense
- Client interactivity = provider islands, not global client sprawl

---

## Route Architecture: Entry + Static + Slots

### Pattern

1. **Entry component (server, request-aware)**
   - Reads params/search/auth/session/cookies
   - Validates access, resolves IDs, prepares dynamic props
2. **Static renderer (server, `'use cache'`)**
   - Renders deterministic layout/content
   - Accepts dynamic UI as slot props (`ReactNode`)
3. **Dynamic slots**
   - Injected from entry component
   - Suspense-wrapped where rendered in static shell

### Why This Works

- Static shell stays cacheable
- Dynamic behavior is explicit and narrow
- Streaming keeps UI responsive
- No accidental full-route dynamic bailout

```tsx
import { Suspense, type ReactNode } from 'react';

type PageProps = { params: Promise<{ slug: string }> };

/** Request-aware server entry. */
export default async function PageEntry({ params }: PageProps) {
  const { slug } = await params;

  const staticData = await getStaticData(slug); // deterministic
  const userData = await getUserData(); // request-dependent

  const dynamicPanel = <PersonalizedPanel userData={userData} />;

  return <PageStatic data={staticData} panel={dynamicPanel} />;
}

type PageStaticProps = {
  data: StaticData;
  panel?: ReactNode;
};

/** Cached static shell. Keep request-volatile reads out. */
async function PageStatic({ data, panel }: PageStaticProps) {
  'use cache';

  return (
    <main>
      <Hero data={data.hero} />
      <Content data={data.content} />
      <Suspense fallback={<PanelSkeleton />}>{panel}</Suspense>
    </main>
  );
}
```

---

## Cache Components Setup & Mechanics

### Enable

```ts
// next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  cacheComponents: true,
}

export default nextConfig
```

Replaces the old `experimental.ppr` flag.

### Three Content Types

| Type | Characteristic | Example |
|------|---------------|---------|
| **Static** | Synchronous, pure computation | `<header><h1>Our Blog</h1></header>` |
| **Cached** (`'use cache'`) | Async but deterministic for given inputs | `db.posts.findMany()` with `cacheLife('hours')` |
| **Dynamic** (Suspense) | Runtime/request-specific, must be fresh | `cookies()`, user session, notifications |

### `'use cache'` Scope Levels

```tsx
// File level — entire module cached
'use cache'
export default async function Page() { /* ... */ }

// Component level
export async function CachedComponent() {
  'use cache'
  const data = await fetchData()
  return <div>{data}</div>
}

// Function level
export async function getData() {
  'use cache'
  return db.query('SELECT * FROM posts')
}
```

### Cache Profiles with `cacheLife()`

```tsx
import { cacheLife } from 'next/cache'

async function getData() {
  'use cache'
  cacheLife('hours')  // Built-in: 'default' | 'minutes' | 'hours' | 'days' | 'weeks' | 'max'
  return fetch('/api/data')
}

// Or inline config:
async function getDataCustom() {
  'use cache'
  cacheLife({
    stale: 3600,      // 1h — serve stale while revalidating
    revalidate: 7200, // 2h — background revalidation interval
    expire: 86400,    // 1d — hard expiration
  })
  return fetch('/api/data')
}
```

Built-in profile shortcuts: `'use cache'` alone → 5m stale / 15m revalidate. `'use cache: remote'` → platform KV. `'use cache: private'` → allows runtime APIs (compliance escape hatch).

### Cache Invalidation

```tsx
import { cacheTag } from 'next/cache'

async function getProduct(id: string) {
  'use cache'
  cacheTag('products', `product-${id}`)
  return db.products.findUnique({ where: { id } })
}
```

**`updateTag()`** — immediate, same-request invalidation:
```tsx
'use server'
import { updateTag } from 'next/cache'

export async function updateProduct(id: string, data: FormData) {
  await db.products.update({ where: { id }, data })
  updateTag(`product-${id}`)  // caller sees fresh data
}
```

**`revalidateTag()`** — background stale-while-revalidate:
```tsx
'use server'
import { revalidateTag } from 'next/cache'

export async function createPost(data: FormData) {
  await db.posts.create({ data })
  revalidateTag('posts')  // next request sees fresh data
}
```

### Cache Key Generation (Automatic)

Keys derived from: build ID + function location hash + serializable arguments + closure variables. No manual `keyParts` like `unstable_cache`.

```tsx
async function Component({ userId }: { userId: string }) {
  const getData = async (filter: string) => {
    'use cache'
    // cache key = userId (closure) + filter (argument)
    return fetch(`/api/users/${userId}?filter=${filter}`)
  }
  return getData('active')
}
```

---

## What Cannot Live Inside `'use cache'`

**Hard rule:** No per-request volatility inside cached boundaries.

| Banned inside `'use cache'` | Why |
|---|---|
| `cookies()`, `headers()` | Request-specific |
| `searchParams` | Request-specific |
| Session/auth reads | User-specific |
| Hidden user logic in helper calls | Invisible request dependency |
| Side effects tied to request lifecycle | Non-deterministic |
| `Math.random()`, `Date.now()` | Execute once at build time inside cache |

### Fix: Extract Outside, Pass as Arguments

```tsx
// Wrong — runtime API inside 'use cache'
async function CachedProfile() {
  'use cache'
  const session = (await cookies()).get('session')?.value  // Error!
  return <div>{session}</div>
}

// Correct — extract in entry, pass as prop
async function ProfilePage() {
  const session = (await cookies()).get('session')?.value
  return <CachedProfile sessionId={session} />
}

async function CachedProfile({ sessionId }: { sessionId: string }) {
  'use cache'
  // sessionId becomes part of cache key automatically
  const data = await fetchUserData(sessionId)
  return <div>{data.name}</div>
}
```

Exception: `'use cache: private'` allows `cookies()` / `headers()` for compliance cases where refactoring is impractical.

---

## RSC Boundary Rules

These interact directly with the static shell pattern.

### Async Client Components Are Invalid

Client components **cannot** be async. Only Server Components can be async.

```tsx
// Bad
'use client'
export default async function UserProfile() {
  const user = await getUser()  // Cannot await in client
  return <div>{user.name}</div>
}

// Good — fetch in server entry, pass data down
// page.tsx (server)
export default async function Page() {
  const user = await getUser()
  return <UserProfile user={user} />
}

// UserProfile.tsx (client)
'use client'
export function UserProfile({ user }: { user: User }) {
  return <div>{user.name}</div>
}
```

### Non-Serializable Props Kill the Boundary

Props from Server → Client must be JSON-serializable.

| Cannot pass | Fix |
|---|---|
| Functions (except Server Actions) | Define inside client component |
| `Date` objects | `.toISOString()` on server |
| `Map`, `Set` | `Object.fromEntries()` / `Array.from()` |
| Class instances | Pass plain object |

Server Actions (`'use server'`) **can** be passed to client components — they're the exception.

---

## Async Patterns (Next.js 15+)

`params`, `searchParams`, `cookies()`, `headers()` are all async. Type them as `Promise<...>` and `await` in the entry component.

```tsx
type PageProps = {
  params: Promise<{ slug: string }>
  searchParams: Promise<{ query?: string }>
}

export default async function Page({ params, searchParams }: PageProps) {
  const { slug } = await params
  const { query } = await searchParams
  // ...
}
```

For synchronous client components that need params, use `React.use()`:

```tsx
import { use } from 'react'

export default function Page({ params }: { params: Promise<{ slug: string }> }) {
  const { sl
Files: 3
Size: 17.1 KB
Complexity: 42/100
Category: Web Dev

Related in Web Dev