Skip to main content
This guide puts an Atomic agent behind an HTTP endpoint using Next.js App Router. The same pattern works in any long-running Node.js server: keep one session per conversation, start one prompt per request, and stream session events back as newline-delimited JSON (NDJSON). Read Use the TypeScript SDK first for createAgentSession(), AgentSession, AgentSessionRuntime, and session events. For servers that release idle sessions and rehydrate them on later requests, wrap sessions with createAgentSessionRuntime() instead (see Releasing idle sessions).

Prerequisites and setup

1

Install @bastani/atomic

Atomic requires Node.js 24.20 or newer. Dependency install scripts are not required; if your package manager blocks install scripts, leave them disabled.
2

Keep Atomic external to the server bundle

Atomic resolves its bundled resources and native modules relative to node_modules, so list it in serverExternalPackages (Next.js 15 and later):
List any other Atomic packages your server imports directly, including @bastani/atomic-storage-postgres when storing sessions in PostgreSQL (see Configure session storage).
3

Use the Node.js runtime and Atomic's TypeBox subpath

Every route handler that imports Atomic must run on the Node.js runtime, not Edge:
Import Atomic only from server code (client components may use import type from @bastani/atomic, which adds zero bytes to the browser bundle). When defining custom tool schemas, import TypeBox from @bastani/atomic/typebox (and its subpaths such as /value, /compile, and /format) so custom formats share Atomic’s validation registry.

Keep one session per conversation

An AgentSession owns the conversation history, so create one per conversation and reuse it across requests. Store shared state on globalThis so next dev hot reloads preserve active sessions without leaking them. Restart the dev server after changing session options because existing sessions keep their creation options.
Sessions stored on globalThis live in one Node.js server process. Run this pattern on a long-lived server with sticky routing per conversation if you scale to multiple instances; short-lived serverless functions discard process memory between requests.
SessionManager.inMemory() keeps history only in RAM. To persist conversations across restarts or share them across servers, pass a SQLite, JSONL, or PostgreSQL SessionManager or sessionStore (see Configure session storage). Call closeConversation() when a conversation finishes or goes idle, and run closeAllConversations() on SIGTERM/SIGINT so session stores and child processes close cleanly.

Stream a prompt

This route starts one prompt and streams the assistant’s output as NDJSON. createTranscript() converts session events into ordered JSON-serializable parts (text, thinking, and toolCall paired with its result). Tool calls appear in message_end before execution begins and gain their result as tool_execution_update and tool_execution_end arrive, so each line carries the full output so far and the browser replaces its rendered list.
Key behaviors:
  • One prompt at a time: session.prompt() rejects while streaming, so the route returns 409 and flips busy synchronously to prevent races. To queue prompts instead of rejecting, call session.prompt(message, { streamingBehavior: "followUp" }).
  • Stop on disconnect: When the browser disconnects or aborts fetch, request.signal and cancel() call session.abort(), stopping the current turn and tools while keeping the session reusable.
  • Payload throttling: Each line emits the complete transcript so far. For long responses, throttle updates on a short timer or send incremental diffs.
  • Structured tool details: createTranscript() returns a tool result’s text by default. Pass createTranscript({ toolResult: (toolName) => (toolName === "todo" ? "details" : "content") }) to emit structured details for specific tools.
  • Error sanitization: Log raw errors server-side and return generic user-safe messages to the browser.

Read the stream in the browser

Render each part by type: text and thinking hold strings, and a toolCall part has name, arguments, and (once progress or completion arrives) result (content, isError, isPartial). Pass an AbortController signal to cancel from the UI.

Secure the endpoint

Atomic has no built-in sandbox. Any HTTP route driving an agent session lets callers execute enabled tools with the server process’s OS permissions, and cwd does not jail file tools to that directory.
  • Require authentication on every route that creates sessions or sends prompts, and scope conversation IDs to the authenticated user.
  • Allow only needed tools. tools is an allowlist; the example enables only read-only read, find, and search. Omit bash, edit, and write unless the agent must mutate files or run commands. Use excludedTools to strip specific tools or noTools: "all" to expose none, and omit ask_user_question in headless servers. See Tools.
  • Disable unused builtins. Turn off subagents, mcp, web-access, and intercom via builtins when not required.
  • Choose cwd deliberately. cwd sets the starting directory for relative paths and project discovery, but tools can still access absolute paths outside cwd. Point cwd at a controlled directory, never user input.
  • Isolate the process in a container, VM, or restricted OS account whenever callers must not reach other server files or when write/shell tools are enabled. See Containerization.
  • Keep credentials server-side. Provider keys live in the server’s ModelRuntime. Never forward them to browsers or accept raw keys from untrusted clients.

Next steps

Use the TypeScript SDK

Sessions, prompting, workspaces, Intercom policies, and lifecycle hooks.

Configure session storage

Persist server sessions in SQLite, JSONL, or PostgreSQL and wire createAgentSessionRuntime().

SDK API reference

Every createAgentSession() option, runtime method, error class, and export.

Orchestration

Multi-step workflows with codemode and subagents, plus migrating older workflows.