Docs · SDK

Node SDK

The Node SDK is in private beta. This page documents the intended surface; it does not claim a public npm package that is not published.

Back to docs
Status

Private beta

Access is provisioned by the team. No public package is promised before it exists.

Availability

Private beta for design partners. Request access through the contact form. When the package is published, this page will show the install command and a CI badge.

Intended surface

Typed client, contacts, campaigns, automations, transactional sends, webhooks and trace lookup.

Example shape

The final package will expose a typed client. The following is illustrative, not an installable API yet.

const client = new LoopNow({ apiKey: process.env.LOOPNOW_KEY });
await client.contacts.create({ email: "asha@example.com" });
A coil of copper cable and a crimping tool on a bone surface.

The short version

  • There is no published LoopNow package on npm. This page documents an early-access client contract for Node, not an install command.
  • The two endpoints that actually run are POST /api/chat, which streams Server-Sent Events, and POST /api/contact, which accepts JSON or form data.
  • Keep every key server-side, set a client timeout shorter than the route’s 45 second upstream deadline, and parse the stream frame by frame.
  • Retry only 429, 502, 504 and transport failures. A 400 or 503 will never succeed on a second attempt.
  • A stream you have already rendered to a user should not be retried silently: the second answer costs tokens and may say something different.

What this page documents, and what it does not

There is no published LoopNow package on npm, and this page will not ask you to install one. The Node SDK is an early-access contract: a typed client is being designed around the two endpoints that already run on loopnow.in, and design partners are writing code against that shape before any package exists. Snippets elsewhere on the site are illustrative and should not be copied into a terminal.

That constraint is useful rather than embarrassing. The surface is small enough that a hand-written client is a transport layer plus a careful stream parser, and you can ship it this week. What a package would add later is not magic: consistent error objects, a retry policy, typed bodies and the boring edge cases around partial frames, aborted readers and sockets that close without a sentinel.

A layered diagram showing a Node application calling a client layer that talks over HTTP to the chat and contact endpoints. Your app Route handler Job runner Client Typed methods Retry policy Transport fetch Stream reader Endpoints /api/chat /api/contact
Figure 1. Where a Node client sits between your application and the two live endpoints, with the key staying on the server side of the boundary.

Everything below is written against real behaviour. The request body, the limits, the status codes and the streaming semantics come from the route serving this site today. The ergonomics around them are the part marked as proposed, and you should treat method names, class names and option keys as provisional until a version is published and pinned.

The chat request body, field by field

The body is deliberately small: an array of messages and an optional page. Each message has a role and content. The route keeps only the last twenty messages, so sending a long history is wasted bytes rather than an error, and it rejects any single content over four thousand characters with a 400. Roles other than user and assistant are coerced, so a stray system message will not do what you hope.

The page field is a location hint. It must start with a slash to be considered, any query string is stripped, and trailing slashes are trimmed before use. The server then prefers knowledge-base passages from that page and its section family when it builds context. Send the pathname the reader is on if you want answers scoped to it, and omit the field entirely for a general assistant.

An annotated breakdown of the chat request body showing the messages array, the page hint and the per-message role and content fields. LoopNow runtime messages last 20 kept role user or assistant content 4000 char cap page pathname hint
Figure 2. The chat body has two top-level fields and one nested object, which is why a typed client for it fits on a single screen.

What you cannot set is just as important. There is no model selector, no temperature, no token ceiling and no system prompt in the request. The route pins the upstream model, samples at a low temperature, caps output and keeps reasoning disabled, all server-side. A client that sends those fields is guessing that they are forwarded. They are not, so leave them out.

  • messages: array of objects, only the last 20 are kept
  • role: user or assistant; anything else is treated as user
  • content: string, 4000 characters maximum per message
  • page: optional pathname starting with a slash, 200 characters maximum
  • rejected fields: model, temperature, max_tokens, system messages

Where the key lives

The assistant key never reaches the browser. The chat route holds it in the worker environment, attaches it to the upstream request and forwards only the streamed text. That means a browser client needs no secret at all, and a Node client usually does not either if it calls the site directly. The key only becomes your problem when you call the model server yourself, which is a different integration from this one.

Read configuration at process start and fail loudly when it is missing. A silent fallback to an empty string produces a 401 from somewhere far away at the moment a user is waiting. Keep local values in an untracked file, inject production values from your platform’s secret store, and make sure the CI pipeline does not echo them. The most common leak is not a compromised host, it is a debug log line with the whole config object in it.

A decision diagram comparing a server environment variable, an edge runtime secret binding and a browser bundle as places to store an API key. Where should the model key live? decision Server env var default for Node Edge binding secret store, not a file Browser bundle never, no exceptions
Figure 3. Three places a key can live, and the one that should never appear in a client bundle at all.

Rotating a key should be boring. Add the new value to the environment, deploy, confirm the new value is the one in use, then remove the old one. If two environments share a key, rotate them together or not at all, otherwise the half-finished rotation looks like a regional outage. Scope keys per environment so a laptop mistake cannot reach production traffic.

Reading the stream without a library

A successful chat response has a content type of text/event-stream and arrives as a sequence of frames separated by blank lines. The route forwards the upstream byte stream unchanged, so the exact frame envelope, including whether a terminal sentinel is sent, follows the model server rather than this page. A robust parser therefore treats a clean socket close and a sentinel frame as equally valid endings.

The trap is chunk boundaries. A network chunk can split a frame in the middle of a JSON object, or contain three frames and half of a fourth. Buffer the decoded text, split on a double newline, keep the trailing fragment for the next read, and only then parse the payload of each complete frame. Parsing per chunk works in development against a fast local server and fails under real latency.

A five-step flow for posting a chat request, checking the status, reading chunks, splitting frames and emitting text deltas. 1 POST JSON 2 Check status 3 Read chunks 4 Split frames 5 Emit deltas
Figure 4. The five stages of consuming the chat stream, where the buffer between stages is what makes partial frames survivable.

Decode with a streaming text decoder so multi-byte characters split across chunks are not mangled; Hindi and emoji both make this visible quickly. Check the response status before touching the body, because failures are JSON with a non-2xx status rather than an event stream. Calling a JSON parser on an error body is harmless; calling it on a half-received stream is not.

Timeouts and cancellation

The route gives the model server forty-five seconds before it aborts the upstream call. Your client should be stricter, not more generous, so that you get a clear local error instead of a truncated stream that looks like a network problem. Thirty seconds for the whole exchange is a sensible default for a chat UI, with a shorter idle watchdog that fires if no frame arrives for several seconds after the first one.

Cancellation needs two halves. Abort the fetch with a controller so the request stops at the edge, and cancel the reader so the response body is released. Without the second half you keep a reader alive on a response nobody is consuming, which on a long-lived server process turns into a slow leak. Distinguish a user cancel from a timeout in your logs; they look identical at the transport layer and mean very different things.

A timeline of a streamed chat request from the initial send through headers, the first delta, an idle window and the final close. 0s Request sent JSON body, no secrets connect Headers received check content type first delta UI can render do not wait for close idle 8s Watchdog aborts surface a retry affordance 45s Upstream deadline route aborts the model
Figure 5. A realistic timeline for one streamed answer, including the idle watchdog that fires before the upstream deadline does.

Platform limits sit outside your code. A serverless function has its own wall clock, and a proxy may have an idle timeout that fires before either of yours. Streaming through a platform that buffers responses defeats the point of streaming entirely, so verify with a slow test that deltas arrive progressively rather than in one burst at the end.

Sorting errors into retry and fail

Error bodies from both endpoints are JSON with an error string and no stack traces. Parse defensively: a proxy or a platform error page may return HTML with a 5xx status, and a client that assumes JSON will throw inside its own error handler. Read the text once, try to parse it, and fall back to the status code plus a truncated body when parsing fails.

The retryable set is short. A 429 means the rate limit was hit, a 502 means the model server answered with an error, and a 504 means the route could not reach it at all. Transport failures such as a reset socket belong in the same bucket. Everything else is terminal: a 400 for invalid JSON, an empty messages array or an over-long message will produce the same 400 forever.

A side-by-side table of retryable chat errors such as rate limits and timeouts against terminal errors such as invalid bodies and missing configuration. Retry with backoff Fail immediately • 429 rate limit• 502 upstream error• 504 upstream timeout• socket reset• idle stream • 400 invalid JSON• 400 no messages• 400 message too long• 503 not configured• 405 wrong method
Figure 6. The status codes that justify another attempt, next to the ones where a retry only delays the inevitable error message.

A 503 deserves special mention because it is configuration rather than load. It means the assistant has no key in that environment, so no amount of retrying will help and the correct user-facing action is to point at the contact form. Alerting on 503 is more valuable than alerting on 500s, because it usually follows a deploy that forgot an environment variable.

Retry maths that do not stampede

Backoff without jitter synchronises your clients. Five hundred tabs that all hit a rate limit at the same moment will all retry at the same moment if the delay is a constant, which reproduces the original failure on a schedule. Use full jitter: pick a random delay between zero and the exponential ceiling, so the fleet spreads out even when the cause is shared.

Cap the ceiling and the attempt count. Four attempts for a chat request is plenty when the delay grows from one second to sixteen; beyond that the user has moved on and a late answer is worse than a clear failure. Keep the budget per request rather than per process, so a retry storm cannot occupy every worker slot while new requests queue behind it.

A bar chart of backoff ceilings in seconds rising from one second to sixteen seconds across four retry attempts. Retry 1 1s Retry 2 2s Retry 3 4s Retry 4 8s Retry 5 16s
Figure 7. Suggested backoff ceilings in seconds for successive retries, before full jitter is applied to each delay.

Chat retries have a cost that ordinary idempotent calls do not. Each attempt runs the model again, bills tokens again and may return different text. Retry only when nothing has been rendered to the user yet, and never splice a retried answer onto a partial one. For contact submissions the risk is the opposite: a retried post can create a duplicate row, and there is no idempotency header on the endpoint today, so deduplicate on your side with a key you generate and store.

Contact submissions from a Node process

The contact endpoint accepts a JSON object or a form body and returns 201 with a success flag for JSON callers. Send the name, email and message at minimum, plus company, phone, intent and consent when you have them. The server trims values, validates the name length and the email shape, caps the message at five thousand characters and stores a hashed IP for rate limiting.

Prefer JSON. A form-encoded post that succeeds answers with a 303 redirect to the contact page, and most HTTP clients follow redirects by default, which turns your API call into an HTML fetch that appears to work. If you must post a form, set the redirect mode to manual so the 303 is visible, or send an accept header for JSON so the route answers with a body instead.

A wireframe of a contact submission flow showing the request, accepted content type, status check, error code and logging. POST contact Accept json Check 201 Read error Log only ids
Figure 8. A contact call from a Node process, with the two places it usually goes wrong: redirect handling and error-code parsing.

Two fields are honeypots: company_url and website. They must be absent or empty for a real submission; a bot that fills every input gets a success response and no row. Consent matters for the stored record, so send it as a boolean rather than a string and keep your own copy of what the user agreed to. Error codes are stable words rather than prose, which makes them safe to branch on.

Finding the slow part

When an answer feels slow, the delay has a location. It can be your bundler shipping a key to the client and the request failing late, a missing client timeout letting a dead socket hang, an edge runtime buffering a stream that should be incremental, or the model itself taking its time on a long prompt. Each has a different fix, and guessing between them wastes an afternoon.

Measure from the outside first. Record the time to first byte, the time to first delta and the time to close, then compare across runs. A large gap before the first byte points at connection or platform issues; a gap between first byte and first delta points at the model; a stream that arrives in one burst at the end points at buffering somewhere between the worker and the browser.

A map of six failure and latency surfaces including bundling, client fetch, edge streaming, the model, the rate limiter and log redaction. Bundler key in output Client fetch no timeout Edge stream buffered body Model 45 second cap Rate limit 12 per minute Logs message text
Figure 9. Six places latency or failure can originate between a Node process and the model, each with a different diagnostic signal.

Rate limits belong in this list because they masquerade as slowness. Chat allows twelve messages per minute per IP, and an office behind one NAT address shares that budget, so the thirteenth message in a busy room gets a 429 while every other user insists the product is fine. Surface the limit to the user instead of retrying into it, and consider a server-side relay if many users share an egress address.

What a published package would change

A hand-written client is not a stopgap you should feel bad about. The contract is small, the endpoints are stable, and the code that calls them is the same code a package would call. The difference appears at the edges: consistent error classes, a shared retry policy, typed response shapes and a single place to fix a parsing bug when one is found.

Structure your own client so the swap is mechanical. Put every request in one module, return your own result type rather than a raw response, map status codes to that type in one switch, and keep the stream parser behind a function boundary. When a package does ship, replacing the module is an afternoon rather than an audit of every call site.

A comparison of a hand-written HTTP client against a planned published SDK, covering control, dependencies, typing and upgrade work. Hand-written client Published SDK (planned) • No dependencies• Full control• You own bugs• Works today• Small surface • Typed surface• Shared retries• Version pinned• Not yet available• Upgrade path
Figure 10. What you get from a hand-written client today against what a published package would add, and why the first is not a compromise.

Do not invent a dependency to fill the gap. Registering or installing a package name that resembles a LoopNow SDK is a supply-chain risk, because an unpublished name can be claimed by anyone. Until there is an official announcement with a version and a registry page, the correct integration is the HTTP contract on this page, written by you, pinned to nothing but the endpoints themselves.

A checklist before you ship

Five things cover most of the risk. The key is read from the environment and absent from the bundle. Every request has a timeout and an abort path. The stream parser buffers across chunks and accepts both a sentinel and a clean close. Status codes are mapped in one place, with retries limited to the retryable set. And the rate limit is a known, surfaced behaviour rather than a mystery.

Test the failure paths deliberately. Send thirteen messages in a minute and confirm the 429 surfaces as a message rather than a spinner. Post an empty body and confirm the 400 is handled. Kill the network mid-stream and confirm the UI does not freeze. These three tests take ten minutes and catch the bugs that otherwise appear only for users on bad connections.

A five-step checklist flow covering key storage, timeouts, frame parsing, error mapping and rate-limit testing. 1 Key in env 2 Timeout set 3 Parse frames 4 Map errors 5 Test the 429
Figure 11. The five checks that turn a working prototype into a client you can leave running in production.

Locally, the chat route needs a model base URL it can actually reach; the repository notes that the worker runtime cannot reach a Tailscale host directly, so a localhost proxy is the development path. That is an environment detail rather than an SDK feature, but it explains most of the first-hour confusion when someone tries to run the site and finds the assistant returning a 504 while everything else works.

Frequently asked questions

Can I install the LoopNow Node SDK from npm today?

No. No package is published, so any install command you see on this site is illustrative. The integration contract lives on this page and targets the two endpoints that already run: chat and contact. If a package name is later announced, it will come with a version and a registry page, and until then the safe approach is a small client you own.

Does the chat endpoint support a system prompt or a model choice?

No. The route owns the system prompt, the model, the sampling temperature and the output ceiling, and it ignores those fields in your request. Roles other than user and assistant are coerced. This is deliberate: the assistant is scoped to answer about LoopNow, and exposing model controls would let a caller turn a product assistant into a general purpose proxy.

How many messages should I send in the messages array?

Send the conversation you need for context, but know that only the last twenty items are read. Each item is capped at four thousand characters, and one over-long item fails the whole request with a 400 rather than being truncated. For long documents, summarise before sending instead of pushing the raw text through the conversation history.

Why does my streamed answer arrive all at once?

Almost always buffering somewhere between the worker and your code. Check that you are reading the response body as a stream rather than awaiting text, that your reverse proxy does not buffer event streams, and that the platform you deploy to supports streaming responses. The route already disables buffering on its side, so the remaining candidate is infrastructure you control.

Is it safe to retry a chat request?

Only if nothing was shown to the user yet. A retry re-runs the model, bills the tokens again and may produce a different answer, so retrying after a partial render can duplicate text or contradict it. Retry transport failures and 429s before the first delta arrives, and after that show a manual retry control instead of retrying behind the user’s back.

What does the 503 from the chat route mean?

It means the assistant has no model key configured in that environment, so the route refuses to call upstream. Retrying cannot fix it and the user should be pointed at the contact form. In practice it appears after a deploy that missed an environment variable, which makes it a deployment alert rather than a runtime load signal.

Do contact submissions need an idempotency key?

The endpoint does not implement an idempotency header today, so a retried post can create a duplicate row. Generate your own submission id, store it with the result, and skip the request when you have already recorded that id. The endpoint’s honeypot fields also need to be present and empty, otherwise the submission is silently accepted and discarded.

How should I store the API key in a Node service?

In the platform secret store or the process environment, never in the repository and never in a value bundled for the browser. Read it once at startup and fail fast if it is missing, rather than defaulting to an empty string. Redact it from logs and error reports, and rotate it by deploying a new value before removing the old one so there is no window with no working key.

What is the rate limit and does it apply per user?

Chat allows twelve requests per minute per IP address, and contact allows five per minute per hashed IP. Both are enforced server-side in D1. Per IP means a shared office connection shares the budget, so a busy room can hit the cap while individual users have sent very little. Surface the limit in the interface rather than retrying into it.

Will my client keep working when the SDK ships?

The endpoints are the contract, and a package would wrap them rather than replace them. If you isolate transport, error mapping and stream parsing behind one module, adopting a published client later is a local change. There is no published version to pin today, so avoid adding a dependency with a guessed name and rely on the HTTP shape documented here.

Sources and further reading

  1. Node.js — Streams API
  2. Node.js — Global fetch and AbortController
  3. Cloudflare Workers — Request and Response objects
  4. RFC 9110 — HTTP Semantics
LoopNow AI Answers from published LoopNow pages
Hi — ask me about LoopNow products, pricing, DPDP or migration. I answer from the published site and can connect you to the team.
Contact page