Guide

Claude Code hooks: a real-world example that tracks your sessions

Claude Code hooks run your own commands when something happens in a session: a prompt is sent, a tool runs, Claude stops. They are how Claude Gains knows how hard Claude worked today. This guide walks through the setup it uses, so you can build your own hook that observes a session without ever getting in its way.

1. Register the hook in settings.json

Hooks live under a hooks key in ~/.claude/settings.json (all projects) or a repo's .claude/settings.json (one project). Each event maps to matchers, and each matcher to commands. Two fields matter for an observer: async, so Claude Code does not wait for the command, and a short timeout in seconds.

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node ~/.claude-gains/app/dist/hook.js",
            "timeout": 5,
            "async": true
          }
        ]
      }
    ]
  }
}

When you install hooks from a script, merge into the existing file instead of overwriting it, write a backup first, and tag your entries (Claude Gains matches on its script path) so an uninstall removes only yours.

2. Pick the events you need

Claude Gains listens to seven events. Each one answers a different question about the session:

EventWhat Claude Gains does with it
SessionStartA session opened. Claude Gains marks it live and notes the project folder.
UserPromptSubmitYou sent a prompt. Marks the session busy. Only the prompt's length is kept, never the text.
PostToolUseA tool finished. Counts the call and its payload size, and keeps the session marked busy.
StopClaude finished its turn. The natural break: tokens are read and a drop may land.
SubagentStartA subagent started. Counts as work in progress, so no workout interrupts it.
SubagentStopA subagent finished. Its transcript is read for tokens too.
SessionEndThe session closed. Final token read, session marked done.

3. Keep the hook fast and harmless

A hook receives the event as JSON on stdin. An observer should do as little as possible: strip anything sensitive, hand the event to something long-running, and exit. No stdout (on some events Claude reads it), no exceptions, exit code 0.

// Read the event from stdin, keep only what you need, send it on.
let input = "";
for await (const chunk of process.stdin) input += chunk;
const event = JSON.parse(input);

// Never keep prompt text or tool payloads: sizes are enough.
if (typeof event.prompt === "string") event.prompt_length = event.prompt.length;
delete event.prompt;
delete event.tool_input;
delete event.tool_response;

try {
  await fetch("http://127.0.0.1:7413/events", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(event),
    signal: AbortSignal.timeout(300), // give up fast
  });
} catch {
  // Daemon down: append to a spool file and replay later.
}
// No stdout, always exit 0: a hook must never change what Claude does.

The heavy lifting happens in a local daemon on port 7413, not in the hook. If the daemon is down, events go to a spool file that it replays on its next start, so nothing is lost and Claude never notices.

4. Get token usage from the transcript

Hook payloads include transcript_path but no token counts. The transcript is a JSONL file where each assistant message records its usage. On Stop, SubagentStop and SessionEnd, read it from the byte offset you saved last time (subagent transcripts sit in a subagents/ folder next to it, named after the session), and upsert usage by API message id so streamed duplicates and re-reads never double count. Claude Gains leaves out cache reads, which would otherwise make long sessions look far heavier than they are.

5. Act only at natural breaks

UserPromptSubmit, PostToolUse and SubagentStart mark a session busy; Stop and SessionEnd mark it idle. Claude Gains only drops a workout right after a Stop, or once every session has been idle for two minutes, so a notification never lands while Claude is still working. The same rule suits anything a hook triggers that needs your attention.

Try it without writing any code

Claude Gains installs all seven hooks, the daemon and a menu bar app in one command, and removes them with claude-gains uninstall.

npx claude-gains init
About Claude Gains →

FAQ

Claude Code hooks FAQ

Where do Claude Code hooks go?+
In a settings file under a top-level "hooks" key: ~/.claude/settings.json for every project, or .claude/settings.json inside a repo for that project only. Each event name maps to a list of matchers, and each matcher to a list of commands.
Do hooks slow Claude Code down?+
A normal hook blocks until it exits, so a slow one adds latency to every event. Mark logging hooks "async": true so Claude Code does not wait, set a short timeout, and keep the script itself fast: no heavy imports, a network budget of a few hundred milliseconds, and a local fallback when the receiver is down.
Can a hook see how many tokens Claude used?+
Not directly: hook payloads carry no token counts. They do include the session's transcript_path, a JSONL file where each assistant message records its usage. Read it from a saved byte offset on Stop, SubagentStop and SessionEnd, and de-duplicate by message id, because streamed messages can appear more than once.
Which hook event means Claude has finished?+
Stop fires when Claude finishes responding to a prompt, and SubagentStop when a subagent finishes. Those are the right moments to do anything that should not interrupt a working session.
How do I remove hooks a tool installed?+
Delete its entries from the hooks section of the settings file, or use the tool's own uninstall command. Claude Gains tags its entries by the hook script path, so claude-gains uninstall removes only its own and leaves your other hooks alone.