Character AI API in JS: Node and Web App Setup
A character ai api js setup comes down to the official openai npm package, a base URL and a server route that keeps your key out of the browser. This page shows the Node code, a streaming Express endpoint and the front-end fetch that goes with it.
Updated

Key points
- The openai npm package works as is: change baseURL, apiKey and the model to
uncensored. - Never ship the key in browser code. Call a small server route instead.
- Streaming uses server-sent events, and one open stream uses one concurrency slot.
- Plain fetch works too if you prefer no dependency.
The short version
You can reach the endpoint from JavaScript in three ways: the openai npm package, plain fetch, or any library that already speaks the OpenAI chat format. The base URL is https://api.characteraiapi.com/v1, the model ID is uncensored, and every request carries Authorization: Bearer <key>. If you do not have a key yet, the API key page explains sign-up and the one-click $0.50 trial.
This is an independent service, not the Character.ai product. It runs one open-weight model that is tuned to answer without content refusals for lawful adult use, and it does not generate images, audio or video. For a character app that is enough: you write the persona, store the conversation and decide how it looks.
Node with the openai package
Create a project, install the package and use ES modules. The examples assume Node 18 or newer.
mkdir persona-chat && cd persona-chat
npm init -y
npm pkg set type=module
npm install openai express
export API_KEY="paste-your-key-here"A first script in chat.js:
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.characteraiapi.com/v1",
apiKey: process.env.API_KEY,
});
const completion = await client.chat.completions.create({
model: "uncensored",
messages: [
{ role: "system", content: "You are Juno, a sarcastic lighthouse keeper. Stay in character." },
{ role: "user", content: "A boat is signalling in the fog. Thoughts?" },
],
temperature: 0.9,
});
console.log(completion.choices[0].message.content);
console.log(completion.usage);Run it with node chat.js. The usage object tells you how many prompt and completion tokens the call used, which you can multiply by $0.15 and $0.50 per million to see the exact price.
Never put the key in browser code
It is tempting to paste the key into a React component and call the API from the page. Do not. Every visitor can open the network tab or the bundled source and copy it, and then spend your balance. The fix is a thin proxy on a server you control. The browser sends the user's message to your route; your route builds the full message list, adds the key and forwards the call.
This also gives you a place to enforce things the API does not know about: a persona that users cannot overwrite, a per-user message limit, and trimming of long histories. A browser should only ever send the new user text and a conversation ID, not the system prompt.
A streaming Express endpoint
Here is a small server with one route. It keeps sessions in memory for the demo; use a database for anything real.
import express from "express";
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.characteraiapi.com/v1",
apiKey: process.env.API_KEY,
});
const PERSONA = "You are Juno, a sarcastic lighthouse keeper. Stay in character, two to four sentences.";
const sessions = new Map();
const app = express();
app.use(express.json({ limit: "100kb" }));
app.use(express.static("public"));
app.post("/api/chat", async (req, res) => {
const { id, text } = req.body;
if (!id || !text) return res.status(400).json({ error: "id and text required" });
const history = sessions.get(id) ?? [{ role: "system", content: PERSONA }];
history.push({ role: "user", content: text });
res.setHeader("Content-Type", "text/plain; charset=utf-8");
try {
const stream = await client.chat.completions.create({
model: "uncensored",
messages: [history[0], ...history.slice(-20)],
stream: true,
});
let reply = "";
for await (const chunk of stream) {
const piece = chunk.choices[0]?.delta?.content ?? "";
if (piece) {
reply += piece;
res.write(piece);
}
}
history.push({ role: "assistant", content: reply });
sessions.set(id, history);
res.end();
} catch (err) {
res.status(err.status === 429 ? 429 : 500).end("error");
}
});
app.listen(3000);The slice keeps the system message plus the last 20 messages. Old turns fall off, which keeps cost steady. Sending only the plain text of each chunk keeps the browser side simple. If you want richer events, send server-sent events instead and parse them on the client.
Server-sent events for richer streaming
Sending raw text works for a demo, but real chat interfaces usually need more than text: a signal when the reply is complete, an error message in the middle of a stream, or the token usage at the end. Server-sent events give you named messages over the same HTTP connection. Your route writes lines in the SSE format, and the browser reads them with a small parser.
// server: inside the route, after setting headers
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
for await (const chunk of stream) {
const piece = chunk.choices[0]?.delta?.content ?? "";
if (piece) res.write(`data: ${JSON.stringify({ token: piece })}\n\n`);
}
res.write(`data: ${JSON.stringify({ done: true })}\n\n`);
res.end();Encoding each token as JSON avoids a classic bug: a token that contains a line break would otherwise break the SSE framing. On the client, read the response body, split on a blank line, strip the data: prefix and parse the JSON. The done message tells the interface to enable the input box again and re-enable the send button.
Handle disconnects. When the user closes the tab, the response object on the server emits a close event. Listen for it and abort the upstream request, otherwise your server keeps pulling tokens that nobody reads, and the stream keeps one of your concurrency slots busy. The OpenAI SDK accepts an AbortSignal in the request options for this purpose.
The browser side
The front end calls your own route, never the API host. Reading a streamed response with fetch takes a few lines:
const id = crypto.randomUUID();
async function send(text, onToken) {
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id, text }),
});
if (!res.ok) throw new Error("request failed: " + res.status);
const reader = res.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
onToken(decoder.decode(value, { stream: true }));
}
}
send("Is the lamp lit?", (t) => { document.querySelector("#out").textContent += t; });Disable the send button while a reply is streaming. It prevents double submits and respects the concurrency limit, because a streamed request occupies its slot until it ends.
Store sessions properly
An in-memory map loses everything when the process restarts and it breaks as soon as you run two server instances. Move sessions into a database or a key-value store as soon as the prototype works. Store the message list as a JSON column, keyed by user and character. When a request arrives, load the list, append the new user message, call the API, append the reply and write the list back.
Decide early who owns the system prompt. Keep it in your code or configuration, not in the stored list that the browser can influence. If the persona is stored with the history, a user could try to overwrite it by crafting a request. Rebuild the message array on the server each time: the system message from config, followed by the stored turns.
Also set a per-user limit. A public chat widget with no limits invites scripted abuse, and every token is billed to you. A counter per user per hour, checked before the API call, is enough to start. Combine it with an upper bound on message length so one request cannot send a megabyte of text. The API accepts bodies up to 8 MB, but your own limit should be far lower, such as 4,000 characters per user message.
Plain fetch, tools and JSON mode
If you want no dependency, a raw call works the same way. Run this from a server, a worker or a script, not from public page code.
const r = await fetch("https://api.characteraiapi.com/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": "Bearer " + process.env.API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "uncensored",
response_format: { type: "json_object" },
messages: [
{ role: "system", content: "Reply with JSON only: {\"mood\": string, \"line\": string}" },
{ role: "user", content: "Juno sees a light on the water." },
],
}),
});
const data = await r.json();
console.log(JSON.parse(data.choices[0].message.content));Tool calling works with the same tools and tool_choice fields the SDK sends. When the model returns tool_calls, run the function and send the output back as a message with role: "tool" and the matching tool_call_id. In a game this is useful for dice rolls, inventory lookups or a lookup of what the character remembers about the player. When streaming, tool calls arrive as partial fragments that you must join before parsing the arguments.
Hosting, limits and cost
Streaming adds a few deployment details that plain JSON routes do not have. Some hosting platforms and proxies buffer responses or cap how long a request may stay open. If tokens arrive in one lump at the end instead of one by one, a buffering layer sits between your server and the browser. Check your platform's documentation for the option that disables buffering for a route, and for any time limit on function execution, since a long roleplay reply can run for many seconds.
For a reverse proxy such as nginx, response buffering is a common culprit and has a setting to turn off per location. For serverless functions, look for a streaming response mode in the platform docs. If your host cannot stream, a small always-on Node process on a cheap server is a reliable fallback.
Finally, put the secret in the host's environment variable store and keep it out of build output. Front-end build tools often inline any variable that carries a public prefix into the browser bundle, so use a name without that prefix, and read it only in server code. A quick check is to search your built files for the first few characters of the key.
Limits, retries and cost
A full key allows 8 concurrent requests and 300 per minute. A trial key allows 2 and 60. Over a limit the API answers with HTTP 429 and the code rate_limited or concurrency. A temporary overload is also a 429 and includes Retry-After: 5. In JavaScript the SDK throws an error with status === 429; catch it, wait, and try again. The SDK also retries a couple of times by default, which you can tune with the maxRetries option on the client.
Cost per turn is easy to estimate. A chat with 2,000 input tokens and 250 output tokens costs 2,000 x $0.15 / 1,000,000 = $0.0003 for input and 250 x $0.50 / 1,000,000 = $0.000125 for output, so $0.000425. A thousand turns is $0.425. Failed or refused requests are not charged. See the pricing page for top-ups from $20 to $500 and the bonus tiers, and the docs for the complete parameter list.