Nov 20, 20269 min read

Claude Code Hooks: Run Backend Checks After Every Agent Edit

Set up Claude Code hooks for a backend repo: a type check after every edit, a Stop hook that runs the tests against local infrastructure before Claude finishes, and a PreToolUse hook that keeps cloud CLIs out of the session, with an Encore example.

Illustration for Claude Code Hooks: Run Backend Checks After Every Agent Edit

Claude Code hooks are shell commands that run at fixed points in a session, such as after every file edit or right before Claude ends its turn. In a backend repo they separate an agent that says the change works from one that has run the tests.

This guide sets up hooks for a TypeScript backend that check each edit, gate the end of every turn on the tests and keep cloud CLIs out of the session.

What are Claude Code hooks?

Hooks are commands that Claude Code runs automatically when a lifecycle event fires, and their exit code decides what happens next: exit 0 lets things continue, and exit 2 blocks or feeds your stderr back to Claude, depending on the event. The hooks guide describes them as deterministic control, so a check always runs instead of depending on the model choosing to run it. These are the events that matter most in a backend repo, per the hooks reference:

EventWhen it firesWhat exit code 2 doesBackend use
PreToolUseBefore a tool call runsBlocks the tool callStop cloud CLIs, migrations against shared databases, force pushes
PostToolUseAfter a tool call succeedsShows stderr to Claude, the tool already ranType check or lint after each edit
StopWhen Claude finishes respondingPrevents Claude from stopping and continues the turnRun the test suite before the turn ends
SessionStartWhen a session begins or resumesShows stderr to the user onlyPrint which local services are running

Where do Claude Code hooks go?

Project hooks live in .claude/settings.json, which you commit so everyone working in the repo, human or agent, gets the same checks, while ~/.claude/settings.json holds hooks for all your projects on one machine, as listed in the settings docs. Hook commands can use $CLAUDE_PROJECT_DIR, the project root where the session started, so scripts in .claude/hooks/ resolve the same way on every machine. This file wires up all three hooks:

{ "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-cloud-cli.sh" } ] } ], "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/typecheck.sh", "timeout": 120 } ] } ], "Stop": [ { "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/backend-tests.sh", "timeout": 600 } ] } ] } }

Matchers filter tool events by tool name, so Edit|Write runs the type check only after file changes. The Stop event has no matcher support and fires every time Claude finishes. Command hooks time out after 600 seconds by default, and the explicit timeout values keep a stuck type check from holding up the session. The scripts below read their JSON input with jq and need to be executable, so run chmod +x .claude/hooks/*.sh after creating them.

How do you run a type check after every edit?

A PostToolUse hook receives the tool's input as JSON on stdin, including tool_input.file_path for the Write and Edit tools. The script below skips anything that is not a TypeScript file, runs the compiler, and on errors writes them to stderr and exits with code 2, which shows them to Claude right after its edit:

#!/usr/bin/env bash # PostToolUse on Edit|Write: type-check the app after each TypeScript edit. file=$(jq -r '.tool_input.file_path // empty') case "$file" in *.ts) ;; *) exit 0 ;; esac cd "$CLAUDE_PROJECT_DIR" || exit 0 if ! out=$(npx tsc --noEmit 2>&1); then echo "TypeScript errors after editing $file:" >&2 echo "$out" | head -40 >&2 exit 2 fi exit 0

Keep this hook fast, since it runs after every edit. tsc --noEmit usually finishes in seconds, while a full test run here would make every small edit slow and push Claude toward fewer, larger edits.

How do you make Claude run the tests before it finishes?

A Stop hook runs when Claude is about to end its turn, and exit code 2 sends it back to work with your stderr as the reason. The input includes stop_hook_active, which is true when Claude is already continuing because of a stop hook, so the script below lets the turn end the second time instead of looping on a failure Claude cannot fix. Claude Code also caps consecutive stop-hook continuations at eight.

#!/usr/bin/env bash # Stop: run the test suite against local infrastructure before the agent finishes. if [ "$(jq -r '.stop_hook_active')" = "true" ]; then exit 0 # already sent back once for failing tests, let the turn end fi cd "$CLAUDE_PROJECT_DIR" || exit 0 if [ -z "$(git status --porcelain -- '*.ts' '*.sql')" ]; then exit 0 # no backend changes in this turn fi if ! out=$(encore test 2>&1); then echo "encore test failed. Fix the failures before finishing:" >&2 echo "$out" | tail -60 >&2 exit 2 fi exit 0

The git status check skips the test run when the turn changed no backend files, such as a question about the code or an edit to the README, which keeps short conversations short.

How do you block risky commands in Claude Code?

A PreToolUse hook on the Bash tool sees the command before it runs, and exit code 2 blocks it with your message shown to Claude. This one blocks Terraform, OpenTofu and the AWS, Google Cloud and Kubernetes CLIs. The pattern treats those names as command words, so a line such as aws s3 ls, terraform apply or ls; gcloud run deploy x is blocked, and a line such as git status is not:

#!/usr/bin/env bash # PreToolUse on Bash: the agent changes infrastructure in code, not from the shell. cmd=$(jq -r '.tool_input.command // empty') if echo "$cmd" | grep -Eq '(^|[;&|[:space:]])(terraform|tofu|aws|gcloud|kubectl)[[:space:]]'; then echo "Blocked: declare infrastructure in the app code and let the deploy provision it, instead of running cloud CLIs from this session." >&2 exit 2 fi exit 0

Pattern matching catches honest mistakes, not determined ones, since a script file or a Python subprocess can run the same command without the word appearing in the Bash input. The real boundary is what the session can reach: an agent that holds no cloud credentials cannot change cloud resources whatever it runs, which is the argument in should AI agents hold cloud credentials.

What should Claude Code hooks not do?

Hooks run with your user's permissions on every matching event, so they should be quick, quiet on success and free of side effects outside the repo. Running the full test suite on PostToolUse, calling external APIs from a hook, or printing secrets from environment variables into stderr all end up in front of the model or slow every step. Flaky tests are worth fixing before adding a Stop hook, because a test that fails at random sends Claude chasing a bug that does not exist.

How does Encore give Claude Code hooks real infrastructure to check?

Encore

Encore is the safe way for AI agents to ship backend changes to your cloud, and in a Claude Code session that starts with the Stop hook above, where encore test runs the tests against the databases and topics the app declares instead of mocks. Per the testing docs, encore test sets up the necessary infrastructure in test mode before running the test script in package.json, with separate test databases tuned for speed.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

The migration adds a unique index on lower(email), so the database enforces the rule even when two requests race:

-- signups/migrations/1_create_signups.up.sql CREATE TABLE signups ( id BIGSERIAL PRIMARY KEY, email TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE UNIQUE INDEX signups_email_lower_idx ON signups (lower(email));

Next to its encore.service.ts, the signups service declares the Postgres database and a Pub/Sub topic in code, and rejects a second signup for the same address in any letter case:

// signups/signups.ts import { api, APIError } from "encore.dev/api"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { Topic } from "encore.dev/pubsub"; const db = new SQLDatabase("signups", { migrations: "./migrations" }); export interface SignedUp { signupID: number; email: string; } export const signedUp = new Topic<SignedUp>("signed-up", { deliveryGuarantee: "at-least-once", }); export const signup = api( { expose: true, method: "POST", path: "/signups" }, async ({ email }: { email: string }): Promise<{ id: number }> => { const existing = await db.queryRow<{ id: number }>` SELECT id FROM signups WHERE lower(email) = lower(${email})`; if (existing) { throw APIError.alreadyExists("email already signed up"); } const row = await db.queryRow<{ id: number }>` INSERT INTO signups (email) VALUES (${email}) RETURNING id`; await signedUp.publish({ signupID: row!.id, email }); return { id: row!.id }; }, );

The test checks the case-insensitive rule against the real local database, which is the kind of behavior an agent breaks when it rewrites a query:

// signups/signups.test.ts import { describe, expect, test } from "vitest"; import { signup } from "./signups"; describe("signup", () => { test("rejects the same email in a different case", async () => { const email = `ada-${Date.now()}@example.com`; await signup({ email }); await expect(signup({ email: email.toUpperCase() })).rejects.toThrow( "email already signed up", ); }); });

Set "test": "vitest run" in package.json so the Stop hook gets a single run instead of watch mode. For a smoke run of the whole app, encore check compiles the app, starts its infrastructure, runs curl commands against it, such as encore check 'curl /signups -H Content-Type:application/json -d {"email":"ada@example.com"}', and exits with code 1 if the app fails to start or any request returns 400 or above, which also fits a Stop hook.

Hooks cover the checks, and Encore's AI integration covers the context: npx skills add encoredev/skills installs skills that teach Claude Code how to use Encore, and the local MCP server lets it query the local databases, call endpoints and read traces, so after the tests pass it can call POST /signups and confirm the publish in the trace. Resource declarations are validated during the build, and capacity, networking and backups are configured per environment outside the code the agent edits.

With infrastructure declared in the same files Claude edits, an agent that adds a topic or a database in one change gets it in the next encore test run with no separate setup, and the hooks check that change against real infrastructure before the turn ends. When the change is pushed, Encore provisions the same resources in your AWS or GCP account.

Best fit: Teams using Claude Code on backends that want every agent turn checked against real local infrastructure, and cloud changes shipped through code review and deploys instead of from the agent's shell.

Frequently asked questions

What are Claude Code hooks?

Hooks are shell commands, HTTP endpoints, prompts or MCP tool calls that Claude Code runs automatically at fixed points in a session, such as before a tool call, after a file edit or when Claude finishes responding. They are configured in settings.json and give you deterministic checks instead of relying on the model to remember them.

How do I make Claude Code run tests before it finishes?

Add a Stop hook that runs the test suite and exits with code 2 when it fails, writing the failures to stderr. Exit code 2 on Stop prevents Claude from stopping, so it reads the failures and keeps working. Check the stop_hook_active field in the input so the hook does not loop forever on a test it cannot fix.

Can a PreToolUse hook stop Claude Code from running dangerous commands?

Yes, a PreToolUse hook on the Bash tool that exits with code 2 blocks the command and shows your message to Claude. It is pattern matching, though, so treat it as a guardrail against mistakes and keep the real boundary in what credentials the session has.

How do I run Encore tests from a Claude Code hook?

Set the test script in package.json to vitest run and call encore test from a Stop hook script, exiting with code 2 and printing the output to stderr when it fails. encore test sets up the app's infrastructure, such as its Postgres databases, in test mode before running the tests, so the agent's change is checked against real local infrastructure.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders