/sitecore-content-sdk-nextjs-app-router:content-sdk-app-router-route-handler-vs-server-actionfrom Sitecore Content SDK - Next.js App Router
Helps choose between Next.js App Router Server Actions and Route Handlers. Explains the auto-refresh side-effect that causes client state loss when Server Actions are used for reads.
Ships in Sitecore Content SDK - Next.js App Router. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Server Actions and Route Handlers both run on the server and can be invoked from client components. They look interchangeable — but they're not. Picking the wrong one for the wrong job produces a class of "page mysteriously refreshes after every interaction" bugs that take hours to diagnose.
'use server' files or src/app/api/... routes.In other words: mutations → Server Action. Reads → Route Handler.
Every Server Action invocation, after returning, triggers Next.js to:
This is correct for mutations: after you write data, you want the UI to reflect the new server state without manual cache busting.
This is catastrophic for reads from client components that hold local state:
User hovers nav item
→ client state: open=true, loading=true
→ fetch via Server Action
← Server Action returns data
→ Next.js auto-refreshes RSC tree
→ entire route re-renders
→ CLIENT STATE IS LOST (NavBranch unmounts/remounts)
→ fresh render: open=false, loading=false, dropdown gone
→ user re-hovers, repeat
This produces the classic "endless loading flicker" symptom. Indistinguishable from a hover-state bug until you realize the page itself is re-rendering.
| Concern | Server Action | Route Handler |
|---|---|---|
| File | Any .ts/.tsx with 'use server' directive, or inline async function in a Server Component | src/app/api/<path>/route.ts with export function GET/POST/... |
| Invocation from client | Direct function call (await myAction(args)) | await fetch('/api/path?...') |
| Type safety | Yes — full TS contract through the function signature | Manual — must parse JSON, validate at boundary |
| Auto-refreshes RSC tree | YES — every call | NO — pure response |
| Cacheable via HTTP | Limited (action-specific) | Yes — standard Cache-Control, Next.js fetch cache, CDN |
| Testable in isolation | Hard (needs RSC runtime context) | Easy — curl, Postman, Vitest with fetch mock |
| Streaming | Limited | Yes via ReadableStream / NextResponse |
| Best for | Mutations (write/delete/update), form submissions, redirects | Reads (GET data, compute, lookup), webhooks, public APIs, BFF endpoints for client components |
// app/posts/[id]/actions.ts
'use server';
import { revalidatePath } from 'next/cache';
import { db } from '@/lib/db';
export async function updatePostTitle(postId: string, title: string) {
await db.posts.update({ where: { id: postId }, data: { title } });
revalidatePath(`/posts/${postId}`); // explicit cache invalidation
}
// app/posts/[id]/EditTitle.tsx
'use client';
export function EditTitle({ id }: { id: string }) {
return (
<form action={(formData) => updatePostTitle(id, formData.get('title') as string)}>
<input name="title" />
<button>Save</button>
</form>
);
}
Why this is right: writing to the DB is a mutation; the auto-refresh ensures the form's surrounding UI (which reads the post title from a Server Component) reflects the new title.
// src/app/api/nav-children/route.ts
import { NextResponse } from 'next/server';
import client from 'src/lib/sitecore-client';
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const parent = searchParams.get('parent');
if (!parent) return NextResponse.json({ error: 'parent required' }, { status: 400 });
const result = await client.getData(NAV_BRANCH_QUERY, { parent });
return NextResponse.json(result.item?.children ?? []);
}
// src/lib/navigation/nav-branch.tsx
'use client';
export function NavBranch({ item }) {
const [children, setChildren] = useState(null);
const onHover = async () => {
const r = await fetch(`/api/nav-children?parent=${item.path}`);
setChildren(await r.json());
};
return <li onMouseEnter={onHover}>...</li>;
}
Why this is right: it's a read; no server state is changing. The hover handler updates LOCAL state. A Server Action would auto-refresh the route and wipe children (and any other client state in the tree).
'use server';
export async function fetchNavChildren(parent: string) {
return client.getData(NAV_BRANCH_QUERY, { parent }); // a READ
}
'use client';
const onHover = async () => {
const children = await fetchNavChildren(item.path); // ← triggers router.refresh()
setChildren(children); // ← state set, then immediately wiped by the refresh
};
Symptom: dropdown opens → data loads → page "reloads" → dropdown closes → user re-hovers → repeat. The page isn't actually doing a hard browser reload; it's an RSC refresh that resets your component tree.
router.refresh() after returning. This is documented but easy to miss. Plan around it.'use server' function to fetch data on hover/click/scroll/visibility, stop and write a route handler instead.router.refresh() boilerplate if you really want a route handler — usually not worth it).revalidatePath / revalidateTag belong inside Server Actions — except for server-to-server webhooks. A Route Handler called by an external system (an Experience Edge publish webhook → /api/revalidate, see content-sdk-app-router-cache-components-and-osr) is the correct home: there is no client to refresh. Any other route handler calling them is a mutation and probably should be a Server Action.Cache-Control: public, max-age=60) or use Next.js's fetch cache to dedupe upstream calls.<form action={...}>) inherently mutate from the user's perspective (POST + redirect/refetch). Server Actions are correct there even when the "action" technically reads.'use server' to a file you just want to "make server-side." Server-side execution and the Server Action runtime are different things. Pure server-side computation in a Server Component is just an async function call, no directive needed.experimental_useOptimistic or manual state-restore. That's papering over the wrong architectural choice. Switch to a route handler.revalidatePath/revalidateTag (which only exist server-side and are awkward to call from a route handler), your other server-rendered UI won't reflect the write.next-action header. Route Handler invocations show up as your declared HTTP method to the route URL.window.__probe = Date.now() before the call and check after. Both should preserve the window object (no full browser navigation), but the RSC refresh from a Server Action will re-render client components from scratch (their state resets), while a Route Handler leaves them alone.- // src/lib/foo/actions.ts
- 'use server';
- import { fetchSomething } from '@/lib/source';
- export async function getSomething(id: string) {
- return fetchSomething(id);
- }
+ // src/app/api/foo/route.ts
+ import { NextResponse } from 'next/server';
+ import { fetchSomething } from '@/lib/source';
+ export async function GET(request: Request) {
+ const id = new URL(request.url).searchParams.get('id');
+ if (!id) return NextResponse.json({ error: 'id required' }, { status: 400 });
+ return NextResponse.json(await fetchSomething(id));
+ }
// some-client-component.tsx
'use client';
- import { getSomething } from '@/lib/foo/actions';
const onSomething = async () => {
- const data = await getSomething(id);
+ const r = await fetch(`/api/foo?id=${encodeURIComponent(id)}`);
+ const data = await r.json();
setData(data);
};
That's the entire migration. The function signature semantics are identical from the client's perspective (both are (id) => Promise<Something>); only the side-effect on the RSC tree differs.
content-sdk-app-router-component-level-navigation — the worked Sitecore example where this skill's rule was learned the hard way (Server Action for a nav lazy-read caused the endless flicker).content-sdk-debug-layout-probe — uses a Route Handler (correctly) for the layout-debug endpoint; another example of "read → handler."useOptimistic (used to mask the refresh delay on Server Actions, not to suppress the refresh): https://react.dev/reference/react/useOptimisticWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
nextjs, app-router, server-actions, route-handlers, client-state
npx claudepluginhub chris1415/sitecore-skills-pocs --plugin sitecore-content-sdk-nextjs-app-router17 skills in this plugin
/content-sdk-app-router-atom-createWrites a Content SDK atom (beta.atoms): atom vs component, field schemas and enum tokens, renderer, catalog and registry keys, container slots, lock lifecycle, mock-MMS proof. Use when adding or changing an atom. Not wiring atoms into an app./content-sdk-app-router-atomsContent SDK Atoms (beta.atoms only): catalog, atomsConfig, ComponentRef rendering, lock CI gate, runtime CSS, Content Kit install, null-render traps. Use when wiring atoms or a low-code component renders nothing. Not code components or stable apps./content-sdk-app-router-cache-components-and-osrOn-demand revalidation (OSR) for a Content SDK App Router app: template choice, version floor, /api/revalidate contract, cache tags, cacheProfile. Use when content is stale after publish. Not Edge webhook setup./content-sdk-app-router-component-data-strategyHow component data flows in a Content SDK App Router app: layout data from getPage, editing data, site and locale from route params, Server vs Client components, BYOC. Use when wiring component props or choosing server vs client./content-sdk-app-router-component-level-navigationNavigation via component-level GraphQL in a Content SDK App Router app: server fetches top levels, client lazy-loads deeper ones via a route handler. Use for main, footer or sidebar nav, or when the SXA nav resolver returns empty./content-sdk-app-router-component-registrationRegisters components in the generated Content SDK App Router component maps (.sitecore/component-map*.ts, never hand-edited). Use when adding a component, a placeholder shows the raw name, or the editor cannot find a component.Other plugins' skills for the same job