Next.js
Brain in a Next.js App Router app — where the client lives, why the Edge runtime cannot load it, identity from the session, recall in a Server Component, writes in Server Actions and after(), and streaming the change feed.
A Next.js App Router project, a Brain API key, and the base URL of an edge
to talk to — your own brain-edge or the Arc gateway. If you
have not met the verbs yet, read Your first memory first; this
page assumes encode and recall mean something to you.
Where Brain fits
A Next app has four places server code runs, and they have different lifecycles, different failure modes, and — this is the one that bites — different runtimes. Before any code, it is worth having the map, because "where does the Brain call go" is most of the integration.
Server Componentrenders the pageRead-only. recall here and the answer is part of the HTML. Runs on
every request once anything in the tree reads a cookie or a header.
Server Actionhandles a mutationWrite here. encode in an action called from a form or a transition, then
revalidate. Dispatched one at a time per client.
Route Handleran HTTP endpoint you ownAnything that is not a page render or a form: a chat endpoint, a webhook, a proxied stream. Full control of the response, including streaming.
after()runs once the response is sentWrites the user should not wait for. The reply streams, and the memory is written behind it.
There is a fifth place — middleware — and it is a special case, because it runs on a different runtime from all four of these. The next section is about that difference, which is the one piece of this integration you cannot design around after the fact.
Install, and which entry to import
npm install @brain-db/sdkOne package, one dependency (cborg, for the wire tier), and two clients
inside it:
BrainHttpClient— JSON over HTTP to the edge. This is the one you want in Next.BrainClient— Brain's native BRN0 wire protocol over a raw TCP socket. More verbs, lower latency, and it needs a socket, which rules out most of where Next code runs.
The package has two entries, and which one you import decides where your code can run:
@brain-db/sdk/httpthe HTTP tier aloneBrainHttpClient and its types. Needs nothing but fetch, so it loads on
every runtime — Node, Edge, Workers, Deno, Bun. Import this one unless
you need the wire client.
@brain-db/sdkboth tiersEverything, including BrainClient and the frame codec. Imports
node:net and node:crypto, so it is Node-only.
Both export the same BrainHttpClient, so on the Node runtime the choice only
changes how much you pull in. Off Node it is the difference between building
and not.
The root entry cannot load on the Edge runtime
export const runtime = 'edge' in a file that imports from the package root
fails the build, because the root entry re-exports the wire tier and the
wire tier imports Node builtins. The error names a module your own code
never mentions, so it is worth recognising:
Error: Failed to collect configuration for /api/edge
[cause]: Error: Failed to load external module node:crypto:
TypeError: Native module not found: node:cryptoThe fix is the import, not the runtime: @brain-db/sdk/http builds and runs
there. The subpath landed in 0.4.1 — on an earlier version there is no
way to take the HTTP client alone, and the Node runtime is the only option.
Prefer the Node runtime anyway
Next 16 warns that "The Edge Runtime is deprecated. You can use the
nodejs runtime instead", and nodejs is the default — you do not have to
declare anything. The subpath matters most for middleware, which runs on the
Edge runtime and cannot be opted out of it, and for a Worker or Deno service
sitting beside your Next app.
With the subpath, a middleware can call Brain directly. Whether it should is
a different question: proxy.ts runs on every matched request including
prefetches, so a recall there is a round trip in front of navigation the user
may never complete. Prefer a Route Handler or the page itself, and reach for
middleware only when the decision genuinely has to happen before routing.
One client, one module
Put the client behind a single module and import that everywhere.
import "server-only";
import { BrainHttpClient } from "@brain-db/sdk/http";
/**
* One client for the whole app. The client is a configuration holder — a base
* URL, a key, a timeout, a retry policy — with no connection state of its
* own, so sharing one across concurrent requests is safe and costs nothing.
*/
export const brain = new BrainHttpClient({
apiKey: process.env.BRAIN_API_KEY!,
baseUrl: process.env.BRAIN_BASE_URL,
timeoutMs: 10_000,
});Three things in that file are load-bearing.
import "server-only". The key must never reach the browser. Without this
line, a Client Component that imports lib/brain fails at runtime in a way
that is easy to miss; with it, the import is a build error naming the file.
Pair it with a plain BRAIN_API_KEY env var — never NEXT_PUBLIC_
anything. A NEXT_PUBLIC_ key is inlined into the client bundle, which hands
every visitor a credential that can read and write your memory space.
timeoutMs: 10_000. The SDK default is 30 seconds. That is a sensible
library default and a bad one inside a page render: on a hosted platform the
function's own limit is often ten seconds, so a 30-second client timeout means
the platform kills the function before the client ever gives up, and you get a
platform error page instead of a handled one. Set the client timeout below
your function limit so your own error path runs.
No baseUrl fallback in code. The SDK defaults to
http://127.0.0.1:8080, which is right for a local brain-edge and wrong
everywhere else. Leaving the variable unset in production means every call
quietly goes to localhost and fails as a transport error rather than an
obvious misconfiguration. Validate it at startup if your app has a place to.
Module scope is the right scope
A new BrainHttpClient per request is not wrong, just wasteful — and the
thing people reach for module scope to get, connection reuse, you already
have: the SDK calls the global fetch, which on Node 18+ is undici with a
keep-alive agent shared process-wide. Connections are pooled whether or not
the client is.
Identity: whose memory is this?
Brain takes its scope from the credential. A key resolves to a
(namespace, space) pair server-side, and there is no scope argument on any
HTTP route — you cannot pass a user id and have Brain file the memory under
it. That is the whole security model: a compromised client cannot read another
tenant's memories by changing a parameter, because there is no parameter.
Which leaves the question of how a logged-in user becomes a scope. Three shapes, in increasing order of isolation:
The third shape — one pooled key with a per-request act_as selector — is the
one most people want, and it is not available over HTTP.
act_as is wire-tier only
act_as is a field on the wire protocol's request frames. The HTTP edge
takes its space from the credential and accepts no selector on any route, so
the pooled-key pattern needs BrainClient over a socket — which, per the
runtime section above, is not something a Next Route Handler should be
opening. If you need pooled-key multi-tenancy, put it in a service that owns
a persistent connection (a FastAPI service is a
natural home) and have Next call that.
For the per-user-key shape, resolve the key where you resolve the session:
import "server-only";
import { BrainHttpClient } from "@brain-db/sdk/http";
import { auth } from "@/lib/auth";
import { keyForUser } from "@/lib/keys";
/**
* The caller's client. One per request, built from the key stored against
* their account — never from anything the browser sent.
*/
export async function brainForCaller(): Promise<BrainHttpClient> {
const session = await auth();
if (!session?.user?.id) throw new Error("not signed in");
return new BrainHttpClient({
apiKey: await keyForUser(session.user.id),
baseUrl: process.env.BRAIN_BASE_URL,
timeoutMs: 10_000,
});
}The rule the shape enforces: the key is derived from the session on the server, never sent by the client. A request body field naming which user's memories to read is an authorization bug however carefully the rest of the app is written.
There is no namespace argument either
Namespace is the tenant wall — one per organisation — and it is likewise carried by the key. See Identity by key for why the constraint is enforced rather than advisory, and Namespaces and spaces for how to lay yours out.
Reading: recall in a Server Component
import { brainForCaller } from "@/lib/brain";
export default async function Dashboard() {
const brain = await brainForCaller();
const answer = await brain.recall({
query: "what is this user working on",
maxResults: 6,
});
if (answer.answerKind === "none") {
return <EmptyState />;
}
return (
<ul>
{answer.memories.map((m) => (
<li key={m.memoryId}>{m.text}</li>
))}
</ul>
);
}Three things about that code are worth more than they look.
answerKind is the answer, not the length of the array
recall returns a membership verdict: "single", "many" or "none".
A "none" is Brain saying nothing stored answers this cue — a real answer,
not an empty page of results. Rendering it as an explicit empty state rather
than an empty list is the difference between "I have nothing on that" and "I
found nothing relevant", and only the first is honest.
Over HTTP the verdict is lowercase — "single" / "many" / "none". Over
the native wire protocol it is the variant name, PascalCase — "Single" /
"Many" / "None". A comparison written against one tier silently never
matches on the other: answer.answerKind === "none" against a wire client
is always false, so the empty state never renders and the page shows a
list of zero items instead.
This page is dynamic, and it must stay that way
brainForCaller reads the session, which reads a cookie, which makes the
route dynamic. That is correct and you should not fight it.
Never cache a recall
A cached recall is one user's memories served to another. The key carries
the scope, so the cache key — a URL, a function argument, a tag — contains
no trace of whose memories these are; two users hitting the same route
produce the same cache entry. If you reach for use cache or
dynamic = 'force-static' on a route that recalls, stop: the only safe
cached recall is one in a genuinely single-space app, and even then it ages
into staleness every time anything is written.
Caching the shell around it is fine, and better than caching the data.
Put the recall in its own component behind <Suspense> and let the rest of
the page prerender.
Latency belongs behind a boundary
A recall is a network round trip to the edge and a read through Brain's pipeline. Putting it in the top-level component means nothing renders until it returns. Give it a Suspense boundary and the page shell streams immediately:
import { Suspense } from "react";
export default function Dashboard() {
return (
<>
<Header />
<Suspense fallback={<MemoriesSkeleton />}>
<Memories />
</Suspense>
</>
);
}
async function Memories() {
const brain = await brainForCaller();
const answer = await brain.recall({ query: "what is this user working on" });
// …
}createdAtUnixNanos is a bigint — nanosecond timestamps are past
Number.MAX_SAFE_INTEGER, so the SDK parses them as bigints rather than
rounding them. JSON.stringify throws TypeError: Do not know how to serialize a BigInt on one, which means Response.json(answer) in a Route
Handler and passing a MemoryHit from a Server to a Client Component both
fail at runtime, not at compile time. Map to your own shape at the boundary
and convert explicitly — Number(m.createdAtUnixNanos / 1_000_000n) for
milliseconds. You should be mapping anyway: MemoryHit carries salience
and confidence, which are internal signals and not things to ship to a
browser.
Tuning the read
recall takes four options beyond the cue, and the defaults are right often
enough that reaching past them is a sign you have a specific problem:
maxResultsnumberoptional1..=1000, server-enforced. The thing it bounds is prompt budget, not
quality — Brain already decided which memories answer the cue, and asking
for thirty does not make the answer better, it makes the prompt longer.
Six to ten is the usual range for a chat turn.
subjectstringoptionalNarrow to a known entity. Use it when the page already knows what it is about — a customer record, a project view — rather than hoping the cue carries it.
scope"space" | "namespace"optional"space" by default — the caller's own space. "namespace" fans out
across every space in the namespace and merges the hits, which is a
deliberate cross-user read and almost never what a per-user page wants.
Case-insensitive, and any other value is rejected rather than quietly
narrowed to the default.
includeTracebooleanoptionalReturns Brain's read-pipeline trace. Free when off, large when on — see the debugging section below before putting it in a hot path.
The option that does not exist is a score threshold. You do not filter hits by
similarityScore yourself; the verdict already encodes that judgement, and
re-thresholding on top of it is how an app ends up discarding the one memory
that answered the question.
Writing: Server Actions
"use server";
import { revalidatePath } from "next/cache";
import { brainForCaller } from "@/lib/brain";
export async function remember(formData: FormData) {
const text = String(formData.get("note") ?? "").trim();
if (!text) return { ok: false, error: "empty" } as const;
const brain = await brainForCaller();
const result = await brain.encode({ text });
revalidatePath("/notes");
return { ok: true, deduplicated: result.wasDeduplicated } as const;
}encode is already idempotent: the SDK attaches a fresh Idempotency-Key per
call and replays the same key across its own retries, so an ambiguous failure
where the write landed but the response was lost replays the original result
instead of storing twice. On top of that, Brain deduplicates byte-identical
text per (space, session), which is what wasDeduplicated reports. Between
the two you do not need client-side idempotency keys for the ordinary case —
a double-submitted form produces one memory.
Server Actions do not parallelize
Next dispatches Server Actions one at a time per client: three triggered in
quick succession run in series, and Promise.all over three actions does
not change that. If a flow needs a recall and a write together, do both
inside one action rather than calling two — or use a Route Handler,
which is not queued this way.
Grouping a conversation: sessions
A memory written with no session belongs to the space and nothing narrower.
That is right for a note or a profile fact and wrong for a conversation, where
you later want this thread, not everything the user has ever said.
A session id is a 64-bit integer you choose, so your own conversation id can be the session id directly — no mapping table:
await brain.encode({ text, session: BigInt(conversationId) });You do not have to create it first: a space or session is created lazily by
the first write that names one. createSession exists for when you want to
attach a title or provision ahead of a write, and it is idempotent on the id,
so calling it on every turn is wasteful but harmless:
const s = await brain.createSession({
sessionId: BigInt(conversationId),
title: "Onboarding call",
});
// s.created tells you whether THIS call made it.Sessions also bound two things worth knowing about: content deduplication is
per (space, session), so the same sentence in two conversations is two
memories; and erasing a session is a single call rather than a hunt for
memory ids. See Erasure when a user asks to be forgotten.
What to write is a product decision
The most common mistake in this integration is not a bug. It is calling
encode on every turn of a conversation, with whatever text happened to be in
the box, and discovering a month later that the space is full of
conversation-shaped fragments with no clean subject that recall cannot do much
with.
Two rules carry most of the weight:
- Write claims, not dialogue. "Priya's standup is at 9:30" retrieves. "ok sounds good, let's do 9:30 then" does not.
- Never write the model's own output back. A reply is not an observation about the user. Store it and the next recall is fed the model's words, so a wrong answer becomes a "fact" the next turn retrieves and repeats. The LangChain adapter has the same warning for the same reason.
What to write is the long version, and it is worth the ten minutes before you ship a write path.
Writing after the response: after()
In a chat app the memory write is not on the user's critical path. They want the reply; the encode can happen once the reply is on its way.
import { after } from "next/server";
import { brainForCaller } from "@/lib/brain";
export async function POST(request: Request) {
const { message } = await request.json();
const brain = await brainForCaller();
const answer = await brain.recall({ query: message, maxResults: 6 });
const context =
answer.answerKind === "none"
? ""
: answer.memories.map((m) => `- ${m.text}`).join("\n");
const stream = await model.stream({ message, context });
after(async () => {
try {
if (isDurable(message)) await brain.encode({ text: message });
} catch (err) {
// Nothing is listening any more — the response is already sent.
console.error("brain encode failed after response", err);
}
});
return new Response(stream);
}Two details decide whether this is a good idea or a silent data-loss bug.
The order is recall, then write. Encoding the user's message first and then recalling with that same message as the cue means the top hit is the sentence you just stored, echoed back. It looks like retrieval working perfectly, which is what makes it hard to notice.
Errors inside after() reach nobody. The response is sent; there is no
status code left to change and no UI left to update. An unhandled rejection
there is a write that silently did not happen. Catch it and log it, and if
these writes matter, count them — a dashboard that shows encodes-attempted
against encodes-succeeded is the only way you will find out.
after() runs after the response, not after the function
The platform keeps the invocation alive to run it, so it is billed and it is bounded by your function's maximum duration. It is the right tool for a single encode and the wrong one for a batch job.
Streaming Brain's change feed
Brain exposes a change feed as Server-Sent Events, and the SDK gives you an async iterable over it:
import { brainForCaller } from "@/lib/brain";
export async function GET(request: Request) {
const brain = await brainForCaller();
const feed = await brain.subscribe();
const stream = new ReadableStream({
async start(controller) {
const encoder = new TextEncoder();
try {
for await (const item of feed) {
if (request.signal.aborted) break;
if (item.kind !== "event") continue;
controller.enqueue(
encoder.encode(
`id: ${item.event.lsn}\ndata: ${JSON.stringify({
memoryId: item.event.memoryId,
text: item.event.text,
})}\n\n`,
),
);
}
} finally {
await feed.close();
controller.close();
}
},
});
return new Response(stream, {
headers: {
"content-type": "text/event-stream",
"cache-control": "no-cache, no-transform",
connection: "keep-alive",
},
});
}What to know before you ship it:
subscribeis not retried and carries no timeout. Both are deliberate: a subscription is long-lived by definition, so a deadline would kill it, and a retry would reopen the feed at its original position and re-deliver everything already seen.- Resume with
fromLsn, do not replay. Every event carries anlsn, and the subscription remembers the last one it saw aslastEventId. Pass that back asfromLsnon reconnect and you resume exactly. Reconnecting without it either replays from the start or skips whatever arrived while you were gone. - Closing the response unsubscribes. The edge tears the Brain-side
subscription down when the HTTP response closes, so breaking out of the
for awaitis the whole teardown. Thefinallyis there for the case where the client vanishes mid-iteration. no-transformis not optional. A proxy or CDN that buffers the response turns a live feed into a stream that arrives all at once, minutes late.
Errors
The HTTP client raises exactly one error type:
class BrainHttpError extends Error {
readonly status: number; // HTTP status, or 0 for a transport failure
readonly code: string; // the edge's stable code, or "transport"
readonly fieldErrors: ReadonlyArray<{ field: string; code?: string; message: string }>;
}Branch on code, never on message — the code is the stable handle and the
message is prose that may change. The full list is on the
Errors page; these are the ones a Next app actually meets:
transport0fatalThe request never got an answer — DNS, connection refused, or the client
timeout fired. Usually a wrong or unset BRAIN_BASE_URL. The SDK has
already retried this.
unauthorized401fatalThe key is missing, malformed or rejected. Not retryable, and not something to surface to the user — it is your configuration.
llm_credential.missing409fatalNo provider credential is registered for the namespace, so the extraction
pipeline's LLM tier cannot run. A 409 rather than a 503 precisely
because retrying will never fix it — a human has to register a key. Surface
it to an operator, not to the end user.
quota.exceeded429retriableA plan ceiling at the edge. Honour Retry-After.
engine.unavailable503retriableBrain is restarting, overloaded, or rate-limiting. The SDK retries this for you on idempotent verbs.
The client already retries — three attempts by default, 100 ms base backoff
doubling to a 2 s cap, on transport failures, 429 and 503, honouring a
server Retry-After when one is sent. Wrapping a call in your own
three-attempt loop gives you nine attempts and a worst case measured in tens
of seconds, inside a function that will be killed before it finishes. Tune
the policy instead:
new BrainHttpClient({
apiKey: process.env.BRAIN_API_KEY!,
retry: { maxAttempts: 2, maxDelayMs: 500 },
});In a Route Handler, translate rather than leak:
import { BrainHttpError } from "@brain-db/sdk/http";
try {
// …
} catch (err) {
if (err instanceof BrainHttpError) {
// 4xx that is our fault, or a 5xx: the user gets neither detail.
const status = err.status === 0 || err.status >= 500 ? 503 : 500;
console.error("brain", err.status, err.code, err.message);
return Response.json({ error: "memory unavailable" }, { status });
}
throw err;
}Degrade, do not fail
Most memory calls are an enhancement, not a precondition. If recall fails,
an agent that answers without context is better than an error page. Decide
that per call site — a chat turn should degrade; a "show me everything you
know about me" page should not pretend it has nothing.
When an answer looks wrong
Two calls answer most of "why did it say that", and both are worth wiring into a dev-only route before you need them at 2am.
whoami answers "whose memories am I reading?" It returns the namespace
and space id the key resolved to, plus the permission bits it carries. A key
pointing at the wrong space produces an app that works perfectly and shows the
wrong data — which looks like a retrieval problem and is not:
import { brainForCaller } from "@/lib/brain";
export async function GET() {
const brain = await brainForCaller();
const me = await brain.whoami();
return Response.json({
namespace: me.namespace,
spaceId: me.spaceId,
canEncode: me.permissions.canEncode,
canRecall: me.permissions.canRecall,
});
}includeTrace answers "what did the read pipeline actually do?" It
returns which retrievers ran, how their ranks were fused, what the filter
chain dropped, and what the reranker moved — enough to tell "the memory is not
there" from "the memory is there and ranked tenth".
const answer = await brain.recall({ query, includeTrace: true });
// answer.trace is a JSON STRING, not an object.The trace does not scale with maxResults
It reports every candidate each lane considered, so it grows with the size of the space, not with the number of hits you asked for. A three-hit recall over roughly 700 memories measured 121 KB, nearly all of it per-lane candidate lists. It costs nothing when off — the server only builds it when asked — so switch it on for one request, not for a route.
It also comes back as a string, deliberately: its ids are 128-bit integers that a JSON number would round. Parse it with a big-integer-safe reader, or read it as text.
If neither explains it, the answer is usually upstream of retrieval: the memory was never written in the shape the cue would match. That is What to write again, and How recall decides explains what the three fused retrievers are each good at.
Testing
The client takes a fetch override, which is the whole seam:
import { BrainHttpClient } from "@brain-db/sdk/http";
const brain = new BrainHttpClient({
apiKey: "test",
retry: { maxAttempts: 1 },
fetch: async () =>
new Response(JSON.stringify({ answer_kind: "none", memories: [] }), {
headers: { "content-type": "application/json" },
}),
});Note the body is snake_case: that is the wire format, and the client
camelCases it on the way in. A stub that returns answerKind produces an
object with answerKind: undefined, and a test asserting the empty path
passes for the wrong reason.
Set maxAttempts: 1 in tests. Otherwise a stub that returns a 503 makes the
test sleep through the real backoff.
Production checklist
Every import is @brain-db/sdk/http unless that file genuinely needs the
wire client. It is the entry that works on every runtime, so making it the
habit means a later runtime = 'edge' or a new middleware import is a
non-event rather than a build failure.
BRAIN_API_KEY and BRAIN_BASE_URL set in every environment, and neither
prefixed NEXT_PUBLIC_. An unset base URL does not fail loudly; it points at
localhost.
Client timeout below the function limit. Ten seconds against a ten-second function means the platform wins; nine against ten means your error path runs.
No route that recalls is cached. Check for use cache, force-static and
revalidate on anything downstream of a recall.
Writes are gated. Something decides what is worth remembering, and it is not "every turn".
after() callbacks catch and log. A silent encode failure there is
invisible by construction.
SDK_VERSION is safe to report from 0.4.1
The exported SDK_VERSION constant is now the version the package ships, so
a health endpoint or an error report can carry it. Below 0.4.1 it was a
stale literal reading "0.1.0" — read it from your lockfile on those.
What you cannot reach from Next
Over HTTP, through a serverless function, some of Brain is simply not available — not because the SDK hides it, but because it needs a persistent connection or a wire-only field:
| Not reachable | Why | Where it lives |
|---|---|---|
act_as per-request identity | Wire-protocol request field; no HTTP route accepts a selector | A service holding a BrainClient |
| Transactions | Multiple ops on one connection, committed together | The wire tier |
| The full 72-verb surface | The HTTP edge serves 60 routes | Wire client |
| Sub-millisecond reads | Each HTTP call is a fresh request through the edge | The wire tier, over a held connection |
None of that is a reason to avoid Next. It is a reason to put the part that needs it behind a service and let Next call that service — which is the same answer as for any other stateful protocol.
Was this page helpful?
Integrations
Five ways to wire Brain into a stack — Next.js, FastAPI, LangChain, the OpenAI Responses API, or the first-party MCP server — and the one question that decides which.
FastAPI
Brain in a FastAPI service — choosing the sync HTTP tier or the async wire tier, why the sync client blocks the event loop, lifespan and dependency wiring, per-tenant identity with act_as, streaming, and error mapping.