📚 Encyclopedia

AI & Claude · updated 2026-10-13

Calling Claude directly from a browser page

anthropic-sdkclaude-apijavascriptbrowserstreaming

The official @anthropic-ai/sdk JavaScript package works inside a browser page with no build step, which is handy for local, single-user tools. It refuses to run in a browser unless you opt in, because a key in page JavaScript is readable by anyone who loads the page. The pattern below was used for the "Arrange" feature of the Story app (~/dev/story, July 2026), which reorders dictated ideas into a coherent draft.

Loading the SDK without a bundler

Dynamically import an ESM build from a CDN, only when the feature is first used, so the rest of the app still works offline:

const { default: Anthropic } = await import("https://cdn.jsdelivr.net/npm/@anthropic-ai/sdk/+esm");

If the jsDelivr +esm build fails in the browser, https://esm.sh/@anthropic-ai/sdk is the usual fallback.

Client and request

const client = new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
const stream = client.messages.stream({
  model, max_tokens: 64000,
  thinking: { type: "adaptive" },
  system: ARRANGE_SYSTEM,
  messages: [{ role: "user", content: text }],
});
stream.on("text", t => panel.append(t));
const final = await stream.finalMessage();

Editing prompts that preserve the author

For "arrange my notes" tasks the system prompt that worked: act as an editor; reorder ideas into a logical flow; smooth transitions; fix dictation artifacts; preserve the writer's voice; invent nothing; reply with only the arranged text. Show the result in a review panel with "use this", "keep both (append under a separator)" and "discard", never overwrite silently.

Security boundary

dangerouslyAllowBrowser is acceptable only when the page is local and the key is the user's own. If the page is ever deployed publicly, move the call behind a small server endpoint (a PHP proxy in Justin's stack) that holds the key in server-side config and enforces auth and rate limits.

See also

Linked from

Sources: story project memory