Text of code.claude.com › docs › en › agent-sdk › session-storage as Styx crawled it on Nov 20, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

Persist sessions to external storage - Claude Code Docs

Documentation Index Fetch the complete documentation index at: /docs/llms.txt Use this file to discover all available pages before exploring further. Skip to main content Assistant Responses are generated using AI and may contain mistakes. By default, the SDK writes session transcripts to JSONL files under ~/.claude/projects/ on the local filesystem. A SessionStore adapter lets you mirror those transcripts to your own backend, such as an object store, a key-value store, or a database, so a session created on one host can be resumed on another host running from a matching working directory.

Common reasons to use a session store: Multi-host deployments. Serverless functions, autoscaled workers, and CI runners don’t share a filesystem. A shared store lets replicas resume each other’s sessions. Durability. Local containers are ephemeral. An external store survives restarts and redeploys. Compliance and audit. Keep transcripts in storage you already govern, with your own retention rules, encryption, and access controls.

The SessionStore interface A SessionStore is an object with two required methods, append and load , and four optional methods. The SDK calls append to write transcript entries during a query and load to read them back for resume. // Exported from @anthropic-ai/claude-agent-sdk as // SessionStore, SessionKey, SessionStoreEntry, SessionSummaryEntry. type SessionKey = { projectKey : string ; sessionId : string ; subpath ?: string ; }; type SessionStore = { // Required append ( key : SessionKey , entries : SessionStoreEntry []) : Promise < void >; load ( key : SessionKey ) : Promise < SessionStoreEntry [] | null >; // Optional listSessions ? ( projectKey : string , ) : Promise < Array <{ sessionId : string ; mtime : number }>>; listSessionSummaries ? ( projectKey : string ) : Promise < SessionSummaryEntry []>; delete ? ( key : SessionKey ) : Promise < void >; listSubkeys ? ( key : { projectKey : string ; sessionId : string ; }) : Promise < string []>; }; type SessionSummaryEntry = { sessionId : string ; mtime : number ; data : Record < string , unknown >; }; # Exported from claude_agent_sdk as # SessionStore, SessionKey, SessionStoreEntry, SessionSummaryEntry. class SessionKey ( TypedDict ): project_key: str session_id: str subpath: NotRequired[ str ] class SessionStore ( Protocol ): # Required async def append ( self , key : SessionKey, entries : list[SessionStoreEntry] ) -> None : ... async def load ( self , key : SessionKey) -> list[SessionStoreEntry] | None : ... # Optional — omit or raise NotImplementedError async def list_sessions ( self , project_key : str ) -> list[SessionStoreListEntry]: ... async def list_session_summaries ( self , project_key : str ) -> list[SessionSummaryEntry]: ... async def delete ( self , key : SessionKey) -> None : ... async def list_subkeys ( self , key : SessionListSubkeysKey) -> list[ str ]: ... class SessionSummaryEntry ( TypedDict ): session_id: str mtime: int data: dict[ str , Any] SessionKey addresses one transcript. projectKey is a stable, filesystem-safe encoding of the working directory, sessionId is the session UUID, and subpath is set when the entry belongs to a subagent transcript or sidecar file rather than the main conversation.

Because projectKey encodes the working directory, resume or continue from the store from a working directory matching the original run’s. In TypeScript, if you set CLAUDE_CODE_PROJECT_DIR_NAME beside CLAUDE_CONFIG_DIR in a query’s env option , the SDK keys that query’s entries, and its resume and continue lookups, by that name instead. Because standalone helpers such as listSessions and deleteSession take no env and read the process environment, set CLAUDE_CONFIG_DIR and the same name in the host process environment too.

Requires Agent SDK v0.3.234 or later. Treat subpath as an opaque key suffix; it follows the on-disk layout, for example subagents/agent-<id> . When subpath is undefined the key refers to the main transcript. Method Required Called when append Yes After each batch of transcript entries is written locally. Entries are JSON-safe objects, one per line in the local JSONL. load Yes Before the subprocess spawns when resume is set or continue: true resolves the newest store session, and once per session when listing falls back from listSessionSummaries .

Return null if the session is unknown. listSessions No By listSessions({ sessionStore }) and by query() / startup() with continue: true . If undefined, continue: true throws, and listSessions({ sessionStore }) throws unless listSessionSummaries is implemented. listSessionSummaries No By listSessions({ sessionStore }) to read metadata for all sessions in one call. Maintain the summaries inside append . If undefined, listing falls back to listSessions plus a per-session load . delete No By deleteSession({ sessionStore }) .

Deleting the main key (no subpath ) must cascade to all subkeys for that session and also remove the session’s summary entry, so a deleted session stops appearing in listSessionSummaries . If undefined, deletion is a no-op, which suits append-only backends. listSubkeys No During resume, to discover subagent transcripts. If undefined, only the main transcript is restored. In a SessionSummaryEntry , mtime is the sidecar’s storage write time and must share a clock source with the mtime values listSessions returns. data is opaque SDK-owned state; persist it verbatim without interpreting it.

Build the entries by calling the exported foldSessionSummary helper, fold_session_summary in Python, on each batch inside append . Skip batches whose key has a subpath ; subagent transcripts must not contribute to the main session’s summary. The fold never sets mtime : stamp it at persist time, through the options.mtime argument in TypeScript or by overwriting the field on the returned entry in Python. Concurrent append calls for the same session can race on the sidecar, so serialize the read-fold-write with a transaction, a compare-and-swap, or a per-session lock; the fold itself is pure.

For what the SDK does with the transcript load returns, see Resume from the store . Quick start The SDK ships an InMemorySessionStore for development and testing. The example below runs a query with the store attached, captures the session ID from the result message, then resumes from the store in a second query() call. The second call passes the same store instance plus resume , so the SDK loads the transcript from the store instead of the local filesystem: import { query , InMemorySessionStore } from "@anthropic-ai/claude-agent-sdk" ; const store = new InMemorySessionStore (); let sessionId : string | undefined ; try { for await ( const message of query ({ prompt: "List the TypeScript files under src/" , options: { sessionStore: store }, })) { if ( message . type === "result" ) { sessionId = message . session_id ; } } } catch ( error ) { // A single-shot query() throws after yielding an error result.

If the // failure was an error result, sessionId was already captured by the loop // above; connection or process failures yield no result message. console . error ( `Session ended with an error: ${ error } ` ); } // Resume from the store. The agent has full context from the first call. for await ( const message of query ({ prompt: "Summarize what those files do" , options: { sessionStore: store , resume: sessionId }, })) { if ( message . type === "result" && message . subtype === "success" ) { console . log ( message . result ); } } import asyncio from claude_agent_sdk import ( ClaudeAgentOptions, InMemorySessionStore, ResultMessage, query, ) store = InMemorySessionStore() async def main (): session_id = None try : async for message in query( prompt = "List the Python files under src/" , options = ClaudeAgentOptions( session_store = store), ): if isinstance (message, ResultMessage): session_id = message.session_id except Exception as error: # A single-shot query() raises after yielding an error result.

If the

The rest of this page is on the live site.