build-nextjs-backend
Skill7 starsChanged 16 days agoMITView on GitHub
Use when building or reviewing the server side of a Next.js 16 App Router app — a server-only data access layer that authorizes every call, Server Actions as public endpoints, route handlers, caching with Cache Components, proxy.ts, env validation and error boundaries.
- Reads credentials
- Installs packages
1 other project uses a version of this.
Adopted by
Most recently taken up by
- VelimirMueller/claude-skillsword for word, first seen Oct 11, 2026
Other versions1 project uses a version of this.
Word for word · 1
- VelimirMueller/claude-skills★ 7100% same
Edited · 0
None found.
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository156 other files it gives its agents.
- skills/swift/swiftui-design-principles/AGENTS.mdAGENTS.md
- skills/swift/ios-code-audit/CLAUDE.mdCLAUDE.md
- skills/swift/swift-focusengine-pro/llms.txtllms.txt
- build-llm-seamSkill
- build-mcp-serverSkill
- build-rag-pipelineSkill
- secure-llm-featuresSkill
- set-up-llm-evalsSkill
- build-supabase-edge-functionSkill
- configure-backend-testsSkill
- design-http-apiSkill
- harden-backendSkill
- scaffold-fastapi-serviceSkill
- scaffold-go-serviceSkill
- scaffold-hono-serviceSkill
- secure-supabase-rlsSkill
- set-up-backend-authSkill
- set-up-background-jobsSkill
- set-up-databaseSkill
- set-up-nextjs-supabase-authSkill
- set-up-observabilitySkill
- set-up-supabaseSkill
- build-cliSkill
- release-cliSkill
- set-up-dev-toolchainSkill
- audit-securitySkill
- audit-toolchainSkill
- extend-skillsetSkill
- promote-releaseSkill
- set-up-stack-profileSkill
- write-commit-messagesSkill
- write-pull-requestsSkill
- analyze-complexitySkill
- apply-algorithmsSkill
- apply-design-patternsSkill
- apply-design-principlesSkill
- apply-solidSkill
- choose-data-structureSkill
- debug-systematicallySkill
- enforce-dependency-ruleSkill
- refactor-safelySkill
- slice-and-estimateSkill
- write-clean-testsSkill
- write-readable-codeSkill
- clean-frontend-scaffoldingSkill
- configure-accessibilitySkill
- configure-analyticsSkill
- configure-ciSkill
- configure-error-trackingSkill
- configure-lintingSkill
- configure-test-stackSkill
- configure-typescriptSkill
- create-moduleSkill
- optimize-performanceSkill
- scaffold-frontend-projectSkill
- set-up-authSkill
- set-up-design-systemSkill
- set-up-document-headSkill
- set-up-error-boundariesSkill
- set-up-feature-flagsSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
2 rules. About 0 are common, 0 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 12
Read .claude/stack-profile.md (frontend.meta: next, backend.track, database, hosting).
- Very specific: line 28
No DAL (data calls in pages or components) → create src/server/ (steps 5–6) and move calls one route at a time.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Build a Next.js Backend
Next.js is the backend here: Server Components read, Server Actions write, route handlers serve webhooks and external clients. The rule that organizes everything: authorization lives next to the data, in a server-only layer, and runs on every call. Pages, actions and proxy.ts do not carry it.
1. Audit current state
Read .claude/stack-profile.md (frontend.meta: next, backend.track, database, hosting). Then:
grep -n '"next"\|"react"\|"typescript"' package.json; ls middleware.ts src/middleware.ts proxy.ts src/proxy.ts 2>/dev/null
grep -n "cacheComponents\|partialPrefetching\|allowedOrigins" next.config.*
grep -rln "'use server'\|\"use server\"" src | xargs -I{} sh -c 'echo "== {}"; grep -c "getViewer\|requireViewer\|auth()" {}' # actions with 0 = no auth check
grep -rn "process.env" src --include=*.ts --include=*.tsx | grep -v "src/libs/env\|src/server/env" # raw env reads
grep -rn "from '@supabase/supabase-js'\|createClient(" src | grep -v "src/libs/supabase" # clients outside the seam
grep -rLn "server-only" src/server 2>/dev/null; ls src/server src/features/*/actions.ts 2>/dev/null
grep -rn "export const \(dynamic\|revalidate\|fetchCache\|runtime\)" src/app # segment configsFindings to report: middleware.ts (renamed proxy.ts in 16), actions without an auth check, DB or SDK access inside components, whole DB rows passed to client components, raw process.env, revalidateTag(tag) with one argument.
2. Decide what to do
- No DAL (data calls in pages or components) → create
src/server/(steps 5–6) and move calls one route at a time. - Actions exist without validation or an auth check → step 5 "actions" first; it is the exposed surface.
- Next ≤ 15 → upgrade first (
proxy.tsis never called on 15; Node 20.9+, TypeScript 5.1+). - Everything present,
pnpm buildpasses → "already in place".
3. Detect the data source and caching model
| Signal | Branch |
backend.track: supabase / @supabase/ssr | Request-scoped Supabase client in the DAL; RLS is the real check (secure-supabase-rls) |
| Drizzle / SQL client | The DAL takes the viewer and filters every query by it; there is no RLS to catch a mistake |
cacheComponents: true | 'use cache', cacheLife, cacheTag, Suspense for request data (nextjs-caching-patterns.md) |
| flag absent | Previous model (fetch cache options, segment configs). New apps from create-next-app have Cache Components on; enable it deliberately in an existing app |
Versions: stack-versions.md.
4. Install only what's missing
pnpm add server-only zod # server-only: Next resolves it itself; install it so lint and tools see itFor Supabase: set-up-supabase and set-up-nextjs-supabase-auth provide src/libs/supabase/* and src/server/auth.ts (getViewer, requireViewer).
5. Generate the seams
Layout (matches the folder standard): src/server/ server-only code, src/features/<domain>/actions.ts thin 'use server' files, src/app/ routing files only.
src/server/env.ts # secrets, server-only
src/libs/env.client.ts # NEXT_PUBLIC_* only
src/server/auth.ts # getViewer / requireViewer
src/server/data/<domain>.ts # DAL: authorize, query, return DTOs
src/features/<domain>/actions.ts
src/app/api/webhooks/<provider>/route.tsEnv — parse once, fail at boot. Client values are read as literal process.env.NEXT_PUBLIC_X (Next inlines only literal reads); server secrets live in a server-only module. Code: nextjs-backend-patterns.md, "Env".
DAL — every exported function authorizes first and returns a DTO, never a raw row:
// src/server/data/notes.ts
import 'server-only';
import { notFound } from 'next/navigation';
import { createClient } from '@/libs/supabase/server';
import type { Tables } from '@/libs/supabase/database.types';
import { requireViewer } from '@/server/auth';
export type NoteDTO = { id: string; body: string; createdAt: string };
const toDTO = (row: Pick<Tables<'notes'>, 'id' | 'body' | 'created_at'>): NoteDTO => ({
id: row.id, body: row.body, createdAt: row.created_at,
});
export async function getNote(id: string): Promise<NoteDTO> {
await requireViewer();
const supabase = await createClient();
const { data, error } = await supabase.from('notes').select('id, body, created_at').eq('id', id).maybeSingle();
if (error) throw new Error(`getNote failed: ${error.code}`);
if (!data) notFound(); // RLS hides other users' rows: "not yours" and "not there" look the same
return toDTO(data);
}Server Action — a public POST endpoint. Authenticate, validate, authorize (the DAL does), act, return a typed result:
// src/features/notes/actions.ts
'use server';
import { refresh } from 'next/cache';
import { unstable_rethrow } from 'next/navigation';
import { z } from 'zod';
import type { ActionResult } from '@/libs/action-result';
import { getViewer } from '@/server/auth';
import { createNote, type NoteDTO } from '@/server/data/notes';
const CreateNote = z.object({ body: z.string().trim().min(1).max(2000) });
export async function createNoteAction(_previous: ActionResult<NoteDTO> | null, formData: FormData): Promise<ActionResult<NoteDTO>> {
if (!(await getViewer())) return { ok: false, code: 'unauthenticated' };
const parsed = CreateNote.safeParse({ body: formData.get('body') });
if (!parsed.success) return { ok: false, code: 'invalid', fieldErrors: z.flattenError(parsed.error).fieldErrors };
try {
const note = await createNote(parsed.data);
refresh(); // per-user data is not cached on the server; re-render the current route
return { ok: true, data: note };
} catch (error) {
unstable_rethrow(error); // let redirect() and notFound() through
return { ok: false, code: 'failed' };
}
}ActionResult (src/libs/action-result.ts), the form component with useActionState, the webhook route handler, and the error boundaries: nextjs-backend-patterns.md.
6. Wire
next.config.ts:cacheComponents: true, partialPrefetching: truefor new code; addexperimental.serverActions.allowedOriginsonly when a reverse proxy forwards a different host; raisebodySizeLimit(default 1 MB) only for upload actions.src/proxy.ts(same level asapp/): session refresh and coarse redirects only; Node runtime; no data fetching (set-up-nextjs-supabase-auth). Renamemiddleware.tstoproxy.tsand the export toproxy.- Pages that read request data (
cookies(),headers(),searchParams,params) wrap that component in<Suspense>; the DAL'sgetViewer()reads cookies, so the same applies. - Self-hosting several instances: set
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY(openssl rand -base64 32) so every instance shares one key. - CI:
next buildprerenders cached pages, so a page reading Supabase through'use cache'needs the API reachable at build (the local stack in CI, or the staging project).
7. Verify
typecheck is tsc --noEmit in a Next.js app (one tsconfig); add "typecheck": "tsc --noEmit" to package.json if it is missing.
pnpm typecheck
pnpm build # Cache Components errors name the exact uncached read or missing <Suspense>
pnpm build && grep -rEl "sb_secret_|SUPABASE_SECRET_KEY" .next/static # prints nothingThen four checks by hand or test: an anonymous request to a protected route redirects; calling a DAL function with no session redirects or throws; a webhook with a bad signature returns 400 and with a good one 200; importing @/libs/supabase/admin from a 'use client' file fails the build.
References
- nextjs-backend-patterns.md — DAL, actions, route handlers, env, errors, proxy rules with code.
- nextjs-caching-patterns.md — Cache Components:
use cache,cacheLife,cacheTag,updateTag,revalidateTag. - ../../frontend/_shared/framework-idioms.md — React 19 idioms the client side follows.
- ../../core/_shared/security-baseline.md — rules 3 and 4.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

