Claude Code hooks

Claude Code SessionStart hook: load context at the start

A SessionStart hook runs when Claude Code starts a new session or resumes one. It is the place to load what Claude should know before the first prompt: recent changes, open issues, notes from earlier sessions.

This page covers when the hook fires, the matchers, how its output reaches Claude, and a hook you can copy. Every statement about Claude Code comes from the official hooks reference and guide, linked at the end.

When the hook runs

Claude Code runs SessionStart hooks when it starts a new session or resumes an existing one. The reference calls the event useful for loading development context, such as existing issues or recent changes to your codebase, or for setting up environment variables.

For static context that needs no script, the reference points to CLAUDE.md instead. Use a hook when the text changes from one session to the next.

SessionStart runs on every session, so keep these hooks fast. Only command and mcp_tool hooks are supported for this event.

In an interactive session, resuming at launch or running /clear, the hooks run in the background and you can type right away. Claude's first response still waits for them to finish, so their context reaches Claude. A prompt you send while they run does not reach Claude until they finish.

Exit code 2 does not block a session start. It shows your stderr to you and nothing more.

The matchers

The matcher says how the session was initiated. Without a matcher, the hook fires on every occurrence.

startup
A new session.
resume
--resume, --continue or /resume.
clear
/clear.
compact
Auto or manual compaction.
fork
A new session forked from an existing one: --fork-session with --resume or --continue, the /fork background copy, /branch, or a conversation you move to the background.

A matcher that uses only letters, digits, underscores, hyphens, spaces, commas and | is read as an exact string, or as a list of exact strings separated by | or ,. So startup|resume|clear|compact fires for four of the five sources and leaves out fork.

What arrives on stdin

Claude Code writes one JSON object to the hook's stdin. Next to the common fields such as session_id, cwd and hook_event_name, a SessionStart hook receives source and, optionally, three more fields:

source
How the session started: startup, resume, clear, compact or fork.
model
The active model identifier. It can be omitted, for example after /clear, so check for the field before you read it.
agent_type
The agent name. Present when you start Claude Code with claude --agent <name>.
session_title
The session's custom title, present when one is set.

When source is resume or fork and the transcript holds at least one response from Claude, the input carries four more fields: seconds_since_last_response, context_tokens, prompt_cache_likely_expired and estimated_cache_write_usd. They need Claude Code v2.1.251 or later. A hook can use them to report what resuming a stale conversation costs.

How the output reaches Claude

Exit with code 0 and print one of two things:

  • Plain text on stdout. Claude Code adds a SessionStart hook's plain-text stdout to Claude's context.
  • One JSON object with hookSpecificOutput.additionalContext. It can carry more fields next to it.

Claude Code wraps the additionalContext string in a system reminder. For this event it inserts the reminder at the start of the conversation, before the first prompt. Claude reads it on the next model request. It does not show up as a chat message. When several hooks return additionalContext for the same event, Claude receives all of the values.

A SessionStart hook can return these fields in hookSpecificOutput:

additionalContext
A string added to Claude's context at the start of the conversation, before the first prompt.
initialUserMessage
A string used as the first user message of the session in non-interactive mode, with the -p flag.
sessionTitle
Sets the session title, with the same effect as /rename.
watchPaths
An array of absolute paths to watch for FileChanged events during this session.
reloadSkills
When true, Claude Code re-scans the skill and command directories after the SessionStart hooks complete.

Rules from the reference

  • Above 10,000 characters, Claude Code writes the text to a file in the session directory. Claude then gets the file path and a preview of up to the first 2,000 characters.
  • Write facts, not commands. The reference gives "The deployment target is production" as a good phrasing. Text framed as an out-of-band system command can trigger Claude's prompt-injection defenses, and Claude then shows the text to you instead of using it.
  • The text is saved in the session transcript. A SessionStart hook runs again when you resume, with source set to resume (or fork with --fork-session), so it can refresh its context instead of replaying stale values.

Example: load memory at the start

This hook reads the last 20 lines of .claude/memory.md and hands them to Claude as additionalContext. It uses only what ships with Node, and a test in our repository runs this exact code.

1. Keep notes in a file

.claude/memory.md holds one line per fact. Write them as statements, for example - 2026-11-02 Tests need DATABASE_URL set.

2. Add the hook

Save this as .claude/hooks/load-memory.mjs:

.claude/hooks/load-memory.mjs
import { readFileSync } from "node:fs";
import { join } from "node:path";

const input = JSON.parse(readFileSync(0, "utf8"));

try {
  const file = join(input.cwd, ".claude", "memory.md");
  const notes = readFileSync(file, "utf8").trim().split("\n").slice(-20);
  const text = notes.join("\n").slice(0, 8000);
  if (text) {
    console.log(
      JSON.stringify({
        hookSpecificOutput: {
          hookEventName: "SessionStart",
          additionalContext:
            "Notes from earlier sessions (session source: " +
            input.source + "):\n" + text,
        },
      }),
    );
  }
} catch {
  // No memory file yet: print nothing and exit 0.
}

When the file is missing or empty, the hook prints nothing and exits 0, and the session starts as usual.

3. Register it

.claude/settings.json
{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "startup|resume|clear|compact",
        "hooks": [
          {
            "type": "command",
            "command": "node",
            "args": [
              "${CLAUDE_PROJECT_DIR}/.claude/hooks/load-memory.mjs"
            ],
            "timeout": 10
          }
        ]
      }
    ]
  }
}

The matcher covers new sessions, resumes, /clear and compaction. The compact entry matters: after compaction the hook puts the notes back. The hooks guide shows the same idea with a single reminder line:

Hooks guide, "Re-inject context after compaction".

4. Check it

Start a new session and ask Claude what the notes say. To see the hook run, start Claude Code with claude --debug.

Ready-made: cachly

The cachly plugin ships a SessionStart hook. At the start of a session it adds a session briefing as additionalContext. The plugin registers the hook without a matcher, so it fires on every start type, compact included, with a timeout of 30 seconds.

The plugin also ships a UserPromptSubmit and a Stop hook.

Claude Code
/plugin marketplace add cachly-dev/cachly-mcp
/plugin install cachly-brain@cachly

Then turn on auto-update once: /plugin → Marketplaces → cachly → Enable auto-update. Claude Code leaves it off for marketplaces outside Anthropic's own, and the hooks update only with the plugin.

More on the other events: Stop hook, PreCompact hook and UserPromptSubmit hook. What survives /compact is covered in Lost context after /compact.

Sources

Checked against the hooks reference on .

More: All Claude Code hook events · AI memory in three layers · MCP integration · All docs