Claude Code & Context Engineering

The CLAUDE.md That Actually Works: A Field-Tested Structure for Astro and Next.js Projects

21 November 2026 · Updated 28 November 2026 · 13 min read · by Yang Kai

A field-tested CLAUDE.md structure for Astro and Next.js that agents actually follow — copy the annotated template and stop repeating yourself.

Template inside: Copy-paste CLAUDE.md template

Contents
  1. The short version
  2. Start with identity, not instructions
  3. The six areas worth covering
  4. The annotated template
  5. Stack
  6. Commands — run these, do not guess them
  7. How we work here
  8. Boundaries — never touch without asking
  9. Content rules (Astro sites only)
  10. Definition of done
  11. When you are stuck
  12. Where the file lives changes what it does
  13. When the file outgrows one page
  14. Astro vs Next.js: what changes
  15. Keep it alive, or it will rot
  16. The quarterly prune: keeping the file true
  17. Common mistakes I still see
  18. Verdict

A CLAUDE.md that works is short, specific, and written from mistakes: stack facts, the exact commands, the hard rules, and a definition of done — nothing else earns the context it costs on every request. This article gives the structure for Astro and Next.js projects, with an annotated template to copy.

I deleted my first CLAUDE.md after three weeks. Not because Claude Code ignored it — because I had written it like documentation for a human who would never join the project. It explained our history, our aspirations, and three different ways to do the same thing. Every session started slower, and the agent still asked about the package manager.

That failure taught me the real job of this file. It is not a README. It is the small set of instructions you would repeat at the start of every single session if you had to type them by hand. If you would not repeat it daily, it does not belong here. Everything else belongs in a skill, a doc, or the code itself — a distinction I unpack in Claude Code Skills, Explained and in AGENTS.md vs CLAUDE.md.

What follows is the structure I now use on both Astro content sites and Next.js apps. The mechanics — where the file loads from, how imports behave, when the docs say a file is too long — are taken from Anthropic’s memory documentation and checked in November 2026, so the advice rests on how the tool actually loads this file, not on folklore.

The short version

If you read nothing else, build these six sections and keep the whole file under 200 lines:

Section What goes in it The test it has to pass
Identity What the project is, who it serves, what you won’t compromise Two or three lines, no history
Stack Framework, language, package manager, deploy target Every fact checkable in the repo
Commands The exact dev, build, check and test commands Copy-paste runnable, never guessed
How we work Diff size, reading before editing, style matching Each rule observable in a finished change
Boundaries Files and actions that need a human first Short enough to memorise
Definition of done Build, tests, and what the agent must report “Done” becomes a check, not a feeling

Start with identity, not instructions

Agents make better trade-offs when they know what the project is for. Two or three lines is enough: who it serves, what success looks like, and what you will not compromise on.

For my Astro sites, that is usually speed and content integrity. For a Next.js product, it might be type safety and not breaking existing routes. Name it once, at the top, and the later rules stop feeling arbitrary.

The six areas worth covering

GitHub’s analysis of more than 2,500 AGENTS.md files identified the areas the good files cover, and an independent scan of 32 real project files found only 7 covered all 6 good-practice areas. I will not list a magic formula here, but in practice the gaps I see — and made myself — are the same: no build command, no test command, no style rule that can be checked, no boundary for what not to touch, no definition of done, and no note on how to handle failure.

A useful CLAUDE.md answers all six in plain language. If a rule cannot be checked, rewrite it until it can. “Write clean code” cannot be checked. “Run npm run build and fix type errors before saying you are done” can. Anthropic’s own guidance makes the same point with plainer examples: “Use 2-space indentation” beats “Format code properly”, and “Run npm test before committing” beats “Test your changes”.

The annotated template

Copy this, delete anything that does not apply to your project, and keep it short. The comments explain why each section exists — remove them once the file is yours if you want it leaner.

# Project: [Name] — [one-line purpose]

## Stack
- Astro 5 / Next.js 15, TypeScript strict, Tailwind
- Package manager: npm (never yarn/pnpm in this repo)
- Deploy: Cloudflare Pages — do not add Vercel-specific config

## Commands — run these, do not guess them
- Dev: npm run dev
- Build: npm run build
- Check: npm run check   # Astro type + content schema check
- Test: npm run test

## How we work here
- Small diffs. One concern per change.
- Read the existing file before editing it.
- Match the style of the file you are in, even if you prefer another style.

## Boundaries — never touch without asking
- .env and .env.* files
- src/content/ published articles (drafts in /drafts are fine)
- Lockfile: never hand-edit package-lock.json

## Content rules (Astro sites only)
- Frontmatter must match the schema in src/content/config.ts
- Dates are YYYY-MM-DD, slugs are kebab-case, no uppercase
- Internal links use trailing slashes: /blog/example/

## Definition of done
- [ ] Build passes
- [ ] No new type errors
- [ ] You summarised what changed and what you did NOT test

## When you are stuck
- Say what you tried, what failed, and what you need.
- Do not invent an API, a prop, or a file path. Search the repo first.

Notice what is missing: no component library tour, no folder-by-folder essay, no copy of your style guide. Those belong elsewhere. I explain the cost of bloating this file in The Context Budget Audit — a large CLAUDE.md is resent on every request, while a skill’s description costs almost nothing until the skill is actually loaded. The size of that gap is the point, even though the exact token counts vary by file.

Where the file lives changes what it does

CLAUDE.md is not one file. Claude Code merges several, in a fixed order from broadest to most specific, and instructions closer to your working directory are read last:

Scope Location Shared with
Managed policy Set by your organisation’s IT (path varies by OS) Everyone in the organisation
User ~/.claude/CLAUDE.md Only you, across all projects
Project ./CLAUDE.md or ./.claude/CLAUDE.md The team, via source control
Local ./CLAUDE.local.md (gitignore it) Only you, in this project

Three loading rules follow from this, and each one changes how you should write:

Not sure what actually loaded? Run /context all in a session and check the list under Memory files. And keep each file under 200 lines: that is the target Anthropic’s documentation sets, with the explicit warning that longer files consume more context and reduce adherence.

When the file outgrows one page

A file pushing past 200 lines has three honest exits. Pick by how often the rules apply.

Split by directory. Move area-specific rules into a nested CLAUDE.md in that folder, where they load only when Claude works there. This is the only split that genuinely reduces cost.

Scope rules with .claude/rules/. Topic files in this directory load at launch like the main file — unless a file carries paths frontmatter naming glob patterns, in which case it loads only when Claude reads or edits a matching file. A testing rule scoped to **/*.test.ts costs nothing during a styling session.

Organise with imports — but know what they do. Any CLAUDE.md can pull in another file with @path/to/file syntax. Relative paths resolve against the file doing the importing, imports can nest up to four hops deep, and imports inside code blocks are ignored. What imports do not do is save context: imported files load at launch, together with the file that imports them. Splitting a 400-line file into four imported 100-line files reorganises it. The bill is identical.

Personal preferences that should never reach the repo — your sandbox URLs, your preferred test data — go in CLAUDE.local.md, loaded after the project file at the same level. And if your repo already carries an AGENTS.md for other tools, a one-line project CLAUDE.md containing @AGENTS.md keeps one source of truth; CLAUDE.md for teams covers the shared-repo version of this setup.

Astro vs Next.js: what changes

The skeleton stays the same. The details change in three places.

For Astro, name the content collections, the schema file, and the image rules. Agents love inventing frontmatter fields. Pin the real ones down, or point to the schema and tell the agent to read it before creating content.

For Next.js, name the router (App Router, in my projects), the data-fetching convention you actually use, and where server-only code lives. The most expensive agent mistakes I have seen in Next.js were not syntax errors — they were a client component quietly importing server code, or a new route duplicating an existing pattern two folders away.

In both cases, add one line about deployment. Agents will happily add a dependency or config that only works on a platform you do not use.

Keep it alive, or it will rot

I review my CLAUDE.md whenever I catch myself repeating an instruction in chat for the third time. That repetition is the signal: promote it into the file, in one checkable sentence. Anthropic’s docs list the same triggers — Claude makes the same mistake twice, a review catches something it should have known, you type the same correction you typed last session. Conversely, when a rule has not mattered in a month, I cut it or move it into a skill.

Two built-in tools help. /init generates a starter CLAUDE.md from your repo (and can fold in other tools’ instruction files), which beats a blank page. And /doctor prompt-audit scans your CLAUDE.md files, rules and skills for outdated or conflicting instructions and proposes edits — nothing changes until you approve them.

That review habit pairs well with the guardrails in 5 Claude Code Hooks That Catch the Mistakes Agents Actually Make, because hooks enforce what prose cannot. The documentation is blunt about this: CLAUDE.md is treated as context, not enforced configuration, so anything that must never happen needs a hook, not a sentence. And if you work in a team or switch tools, read Subagents vs One Long Session next — a clear CLAUDE.md is what makes delegation safe.

The quarterly prune: keeping the file true

A CLAUDE.md decays the same way a codebase does — by accretion. Every incident adds a rule; nobody removes the rules whose incidents can no longer happen. Schedule a prune once a quarter, and run it like an audit rather than a tidy-up. Print the file and mark each rule with one of three verdicts.

Load-bearing: removing it would reproduce a mistake you have actually watched happen — these stay, and they are usually fewer than half the lines. Covered elsewhere: the rule restates something the linter, the type system or the test suite now enforces mechanically — delete it, because a rule the tooling enforces is context spent twice. Fossil: the rule references a file, a service or a habit the project no longer has — delete it and check git history if you are unsure why it was written.

Two signals tell you the prune is overdue: the agent starts ignoring a rule you know is in the file (long files get skimmed, by agents as by humans), and new rules get added at the bottom because nobody remembers the section they belong in. The target is not a line count; it is a file where every line can answer the question “what goes wrong without you?”

One newer option softens the whole chore: Claude Code’s auto memory lets Claude keep its own notes from your corrections, in a separate file that loads alongside CLAUDE.md. It does not replace rules you care about — you do not control its wording — but it absorbs some of the small preferences you would otherwise keep promoting by hand.

Common mistakes I still see

Writing the file once and never pruning it. Putting secrets or example keys in it. Giving contradictory rules in different sections — agents will pick one, and not always the one you wanted. And the subtle one: describing the project you wish you had, instead of the repo as it is today. The agent works in the repo as it is.

Start small, run a real task, watch where the agent guesses, and fix the guess with one line. That loop, repeated for a week, produces a better file than an afternoon spent writing a perfect one in advance.

Verdict

A working CLAUDE.md is a short, checkable contract: identity, stack, commands, working rules, boundaries, and a definition of done — under 200 lines, split by directory or path-scoped rules when it grows, and pruned on a rhythm. Copy the template, delete everything that is not your project, and let real mistakes write the rest one line at a time.

If you have never written one of these files, start smaller: your first CLAUDE.md walks through a minimal version you can grow into this setup. If you want the production version rather than building it piecemeal, I packaged my own files in the Claude Code Workflow Pack, with more free templates on the resources page and site starters under themes. Long projects add a second problem — decisions made in week one vanishing by week six — which context budgets for long projects tackles directly.

FAQ

How long should a CLAUDE.md be? Anthropic’s documentation targets under 200 lines per file, because longer files consume more context and reduce adherence. Most single projects are well served by 40–80 lines. If yours is past 200, some of it belongs in nested files, path-scoped rules, or skills — The Context Budget Audit shows how to decide line by line.

What is the most valuable section? The definition of done. “Run the build, run the tests, show me the output” in writing ends more bad sessions than any other single rule, because it converts “finished” from a feeling into a check.

Should I copy a template wholesale? No — start from one, then delete every line that does not describe your project. A template’s value is its structure; its content is someone else’s project, and wrong instructions are worse than none.

How often should I update CLAUDE.md? When you catch the agent repeating a mistake, and only then. Each addition should trace to a real incident; speculative rules accumulate into the swollen files this article exists to fix.

Category: Claude Code & Context Engineering · Tags: #claude-code #claude-md #astro #nextjs #ai-coding

Next step: this article is part of Claude Code guides, which covers the full topic from first setup to advanced use.

Related guides