The SDK on the web: the browser, Node.js and server rendering
Web apps use the SDK as an npm package, @squiddy-cloud/sdk: the SDK compiled to JavaScript, a library of ES modules with TypeScript declarations, and an API written for JavaScript: plain objects, callbacks that return the function that stops them, and a Promise. The same package runs in a page and, from 0.7.0, in Node.js, so a server that renders the pages of a web app (Next.js, Remix) reads the configuration itself and hands it to the page, which arrives configured. What the SDK does, what the API key allows and how the SDK behaves offline are on the SDK page; this page is the integration. A web app written in Kotlin, compiled to JavaScript or to WebAssembly, uses the Kotlin API from Maven Central instead: Kotlin Multiplatform.
Install
npm install @squiddy-cloud/sdk@0.9.0
The package is on npm, at version 0.9.0, the same release as on the other platforms. With a bundler (Vite, webpack, esbuild, Rollup) the page imports it by name. Without one, a <script type="module"> imports it through an import map that names the package's module:
<script type="importmap">
{ "imports": { "@squiddy-cloud/sdk": "./node_modules/@squiddy-cloud/sdk/squiddy.mjs" } }
</script>
<script type="module" src="./main.js"></script>
| Minimum | a browser with ES modules, fetch and localStorage: any current Chrome, Edge, Firefox or Safari; Node.js 22.3 or later |
| Runtime | a page, and Node.js (in Node.js), which server rendering builds on; not the Edge runtime of Next.js (where it runs) |
app_type sent to Squiddy | web, in a page and in Node.js |
| Bundle id | the page's host name, location.hostname; required in Node.js |
| Storage | the page's localStorage, under keys that start with cloud.squiddy.sdk/; in Node.js a directory of the app, or the memory of the process |
| Size | about 1 MB of JavaScript once bundled and minified, about 0.3 MB with gzip; 23 ES modules and about 3.1 MB unbundled |
The package has one dependency, ws, which belongs to Ktor, the HTTP library inside the SDK: Ktor names it only for WebSockets on Node.js, which the SDK never opens. The browser never loads it, but a bundler resolves every import it finds, and takes the browser stub that ws ships.
Where it runs
The package finds out where it runs when initialize is called, from the global object:
- a page: the browser's
localStorage, its visibility and its language, as the rest of this page says. A page simulated in Node.js (jsdom, in the tests of a React app) has adocument, so it stays a page; - Node.js, 22.3 or later: a JavaScript that states a version of Node.js (
process.versions.node) and has nodocument, such as a Next.js or Remix server, an API, a script. In Node.js says what changes; - not the Edge runtime of Next.js (
export const runtime = "edge"), which is neither: render the pages that read Squiddy with the Node.js runtime, Next.js's default. Deno and Bun are not tested; a server on them, or in another language, reads Squiddy with the plain call of the TypeScript example, with no SDK.
There is no push update, in a page or in Node.js: Squiddy's Push update reaches the installations of an app through topics of Firebase Cloud Messaging, which a page cannot subscribe to, and a page already checks whenever it becomes visible again.
Keep the key out of the repository
The key ends up in the page's JavaScript, which every visitor's browser downloads, so it is not a secret (see the API key). Like any credential it still does not belong in the repository: the build injects it. With Vite, a .env.local file, which Vite's projects tell git to ignore, and the variable it exposes to the page:
# .env.local: never committed
VITE_SQUIDDY_API_KEY=sqd_…
const apiKey = import.meta.env.VITE_SQUIDDY_API_KEY;
Other bundlers have their own way, such as esbuild's define. A pipeline writes the same variable from a secret variable before it builds.
Initialize
Create one instance per page and Squiddy environment, when the page starts, and keep it for the life of the page: there is no global instance and no automatic start. A module of its own is the place, imported by the code that reads the configuration:
// squiddy.ts
import { initialize } from "@squiddy-cloud/sdk";
export const squiddy = initialize({
host: "https://squiddy.example.com",
apiKey: import.meta.env.VITE_SQUIDDY_API_KEY,
appId: "my-app",
appVersion: "2026.11.19", // YYYY.MM.DD: Squiddy compares it as a number
appMode: "release",
});
initialize checks every option before it creates anything, its type included, since JavaScript passes whatever it has, and throws an Error that names the option to fix: a missing or empty one, a version that is not YYYY.MM.DD, a host that is not an http or https URL. A member it does not know, such as the refreshIntervalMillis of 0.2.0, is ignored. It returns at once, touching neither the network nor localStorage: the SDK reads and writes them in later tasks of the page's event loop, and config stays pending until the stored configuration is read; with an initialState it is ready from the call itself (server rendering). close() stops the updates and the listeners.
Options
Only the first five are required; the others may be left out.
| Option | Default | What it does |
|---|---|---|
host, apiKey, appId, appVersion, appMode | — | Required, as strings. appVersion is YYYY.MM.DD; appMode is matched against the configuration's modes, such as debug and release |
customParams | none | An array of the custom parameters the configuration's rules match, sent as given |
bundleId | the page's host name | Another identifier, sent as given. A page without a host name, such as a file: URL, must give one |
language | the browser's | A language of the page's own, sent as given; setLanguage changes it later |
entityId | the installation id | An opaque id of yours that rollouts place the visitor by (see rollouts) |
timeoutMillis | 10 000 | The longest one call may take, in milliseconds |
logger | none | A function (level, message, cause): debug lines show the HTTP headers with the key redacted, warning lines the problems the SDK recovered from, such as a localStorage the browser refuses |
storageDirectory | the memory of the process | In Node.js only, the directory where the SDK keeps its files (in Node.js); a page does not read it |
initialState | none | In a page rendered on a server, the state the server serialized (server rendering) |
How often the SDK checks while the page stays visible is not an option: the configuration decides it with the refreshInterval of its web API block, and by default there is no periodic check. A page cannot receive the push update, so one that must notice a new configuration while it stays open needs the field. The periodic check says how, and how the calls of the visitors count against the key's limit.
The configuration
config, gate and strings are values to read now, and each has its listener: onConfig, onGate and onStrings call it with the value now, in a later task, and then with every change, and return the function that stops it. settled() is a Promise of the first state that is not pending.
const stop = squiddy.onConfig((state) => {
if (state.configuration) apply(state.configuration); // ready, or failed with the last valid one
});
const first = await squiddy.settled();
const timeout = squiddy.config.configuration?.serverApi?.setting("timeout")?.asInt();
A state has a kind: pending, ready or failed. A ready state has its origin, cache from the browser's storage or network once Squiddy sent or confirmed it; a failed one has its error and the configuration still served. A check that finds the configuration unchanged emits nothing. A configuration has its version, its serverApi (baseUrl, mode, apiVersion, isDebugActive and settings, with setting(key)), its two notices appUpdate and infoPoint, and its strings. A setting reads as text with value, or with asInt(), asDouble() and asBoolean(), which throw an Error naming the setting when the value is not of that type.
Every value is the same object while it does not change, so a page compares values with ===, and React reads one with useSyncExternalStore:
const state = useSyncExternalStore((onChange) => squiddy.onConfig(onChange), () => squiddy.config);
A listener that throws is reported as an uncaught error of the page and keeps listening.
The gate
gate says which screen the page shows:
squiddy.onGate((gate) => {
switch (gate.kind) {
case "maintenance": showMaintenance(gate.title, gate.message); break;
case "update_required": showUpdate(gate.title, gate.message); break;
default: showApp();
}
});
update_required comes from an app-update notice marked as required for this version, maintenance from an info-point notice that halts the app, and when both apply maintenance wins. Titles and messages arrive already localized by Squiddy; a title or a message left blank for the language arrives empty, and the gate applies all the same. The gate holds for the configuration read from the browser's storage too, so a maintenance stays on screen offline, and it is none while there is no configuration at all. In a page, an update usually means a reload: the version is built into the page, so the site serves a new build and the notice asks the visitor to load it. The notices stay readable one by one, with their flags, in configuration.appUpdate (isRequired) and configuration.infoPoint (isHalting).
The kinds are closed sets, like the SDK's types on the other platforms: until 1.0.0 a minor version may add one, and says so in the changelog, so keep a default branch.
Strings
const title = squiddy.string("welcome_title", "Welcome");
A string is looked up in the language the SDK asks in, then in the configuration's default language, then the fallback (string(key) without one returns null), and only a key the language does not have goes on to the next. From SDK 0.4.0 an empty text is a text: a translation left blank in the dashboard is returned empty, with or without the fallback, so a key left blank in a language stays blank in the page. Up to 0.3.0 the SDK skipped an empty text and fell back to the default language. strings is the value of all of them, and onStrings its listener, for a page that redraws when they change. The configuration holds every language its API block supports, so a change of language changes the strings at once, without a call.
Language
The SDK asks Squiddy in the primary language of navigator.language (it for it-IT), and follows the browser's languagechange event while the page is open. A page with its own language picker calls squiddy.setLanguage("en"), and setLanguage() goes back to the browser's; a blank language, or one that is not a string, throws an Error. When the language changes, the strings switch at once, and the SDK checks with Squiddy, while the page is visible, for the texts of the notices, which Squiddy localizes for each call.
When the SDK checks
At every start, after serving the stored configuration; whenever the page becomes visible again (document.visibilityState, the visibilitychange event); and, if the API block of the configuration has a refreshInterval, at that interval while it stays visible (the periodic check). A hidden page, in a background tab or a minimized window, makes no call. squiddy.refresh() checks at once, and the outcome arrives in config.
In Node.js
The same package runs in Node.js 22.3 or later, for a server that renders the pages of a web app or reads its configuration in its backend:
// squiddy.server.ts: imported by server code only
import { initialize } from "@squiddy-cloud/sdk";
export const squiddy = initialize({
host: "https://squiddy.example.com",
apiKey: process.env.SQUIDDY_API_KEY,
appId: "my-app",
appVersion: "2026.11.19",
appMode: "release",
bundleId: "shop.example.com", // required: a process has no host name
language: "en", // or setLanguage(): see below
storageDirectory: "/var/lib/shop/squiddy", // optional: without it, the memory of the process
});
- The bundle id is required, since a process has no host name. A server that renders a site's pages passes the site's host name, the bundle id its pages send, so both read the same configuration. The requests declare the web app (
app_typeweb) for the same reason. - The storage is the
storageDirectoryoption, absolute or relative to the working directory, private to the app and created by the first write: the last configuration and the installation id, so a restart serves the configuration before the network answers. Without it, the memory of the process, shared by its instances, for as long as it runs. The directory needs Node.js 22.3 (or 20.16): an older Node.js refuses it atinitialize. - No background: the SDK checks at once and then, as long as the instance is open, at the
refreshIntervalof the configuration's API block (the periodic check). Without one, a server checks only when it starts and whenrefresh()is called, so give thewebblock of a configuration a server reads arefreshInterval. - The language is the
languageoption orsetLanguage, or else the process's default locale (LANG). A server that renders pages for visitors of several languages keeps one instance per language, made the first time a page needs it and kept:setLanguageon one shared instance would change the language of every request at once. - One instance per process, or per language, made once and kept, as in a page: never one per request, which would call Squiddy at every page.
- A listener that throws is an uncaught exception of the process, as Node.js makes one of a listener of an
EventTarget, and stops a server that does not handle those: catch inside the listener. fetchis Node.js's own. A process that replaces its global dispatcher with the one of theundicipackage (jsdom does, in the tests of a React app) can make it refuse the SDK'sContent-Lengthheader: leave Node.js's own in place in a process that runs the SDK.
React
React apps read the same values in components with the hooks of @squiddy-cloud/react, the same on the web and in React Native: a provider holds the instance the app created, and each hook follows one value with React's useSyncExternalStore, so a component renders again only when what it reads changes.
npm install @squiddy-cloud/react@0.9.0 @squiddy-cloud/sdk@0.9.0
import { SquiddyProvider, useSquiddy, useSquiddyGate, useSquiddyString } from "@squiddy-cloud/react";
import { squiddy } from "./squiddy";
export function App() {
return (
<SquiddyProvider squiddy={squiddy}>
<Home />
</SquiddyProvider>
);
}
function Home() {
const gate = useSquiddyGate(); // none, update_required or maintenance
const title = useSquiddyString("welcome_title", "Welcome"); // an empty text stays empty
const instance = useSquiddy(); // for setLanguage and refresh
if (gate.kind !== "none") return <Notice title={gate.title} message={gate.message} />;
return <h1 onClick={() => instance?.setLanguage("it")}>{title}</h1>;
}
| Hook | What it returns |
|---|---|
useSquiddyState() | config of the instance: pending, then ready (with its origin) or failed (with its error and the configuration kept) |
useSquiddyConfig() | the configuration to use, or null while there is none |
useSquiddyGate() | the gate, with the title and the message Squiddy localized |
useSquiddyString(key, fallback?) | the string of key, as string(key, fallback) reads it: only a missing key gives the fallback |
useSquiddy() | the instance itself, for setLanguage and refresh, or null |
The provider neither creates nor closes the instance: the app creates it once, outside its components, and keeps it. A hook outside a provider throws an error that names SquiddyProvider. The hooks need React 18 or later, and the package's version is the SDK's.
On the server. On the server (Next.js, Remix, any rendering of client components in Node.js) and while React hydrates the server's markup, the hooks read no instance: they return the provider's initial values, the configuration the server read (server rendering), or, without them, the initial state: pending, no configuration, the gate none, the fallback of each string. Either way the server's markup is the browser's first one, and React renders again with the instance's values right after hydrating. Without a state from the server, the provider gets null on the server:
const squiddy = typeof window === "undefined" ? null : initialize(options);
The package is the JavaScript compiled from the hooks' TypeScript, with its declarations, and its entry is a client module ('use client'): in React Server Components, the provider and the hooks belong to client components, and Next.js takes the package without transpilePackages.
Server rendering
A page rendered on a server can arrive with its configuration already in it: the server reads the configuration with an instance of its own (in Node.js), serializes it into the page, and the page starts from it, so the visitor sees the configured page, its gate included, before any call of the browser. Three functions do it:
| Function | Where | What it does |
|---|---|---|
serialize(squiddy) | on the server | The configuration the instance holds, as a string to put in the page: the configuration with its fingerprints, when it arrived and the language it was asked in, never the key nor the installation id. null before the first configuration, so the server awaits settled() first |
restore(state) | on the server and in the page | The values the page starts from, read from the state without an instance: config (ready, with the origin cache), gate, strings and string(key, fallback). The same on both sides, so the browser hydrates the server's markup; without a state, an instance's initial values |
initialize({ ...options, initialState: state }) | in the page | The page's own instance, ready at once with the server's configuration, from the call itself. It keeps the configuration in localStorage in place of the one stored there, and its first check sends the state's fingerprints: an unchanged configuration costs a not_modified |
The state is opaque, and read by the same release of the SDK: a string serialize did not make is refused with an Error, by restore and by initialize, so the server and its pages deploy one version. What the server and the page read is the same configuration when they send the same bundleId (the site's host name) and the same language: the server passes both to the page. A rollout or a rule that resolves another configuration for the visitor, such as a percentage rollout by the visitor's installation id or a custom parameter only the page knows, arrives with the page's first check.
Next.js (App Router). The server keeps its instances, one per language, for as long as it runs; a Server Component serializes what the instance of the visitor's language holds; a client component gives the hooks the restored values and creates the page's instance after hydration:
// lib/squiddy.server.ts: one instance per language, made the first time and kept
import { initialize, serialize, type Squiddy } from "@squiddy-cloud/sdk";
const instances = new Map<string, Squiddy>();
export async function squiddyState(language: string): Promise<string | null> {
let squiddy = instances.get(language);
if (!squiddy) {
squiddy = initialize({ ...options, bundleId: "shop.example.com", language });
instances.set(language, squiddy);
}
await squiddy.settled();
return serialize(squiddy) ?? null;
}
// app/page.tsx: a Server Component, rendered for every request
import { Providers } from "./providers";
import { squiddyState } from "@/lib/squiddy.server";
export const dynamic = "force-dynamic";
export default async function Page() {
const language = "en"; // the visitor's, from the route or Accept-Language
const state = await squiddyState(language);
return (
<Providers state={state} language={language}>
<Home />
</Providers>
);
}
// app/providers.tsx
"use client";
import { useEffect, useState, type ReactNode } from "react";
import { initialize, restore, type Squiddy } from "@squiddy-cloud/sdk";
import { SquiddyProvider } from "@squiddy-cloud/react";
export function Providers({ state, language, children }: { state: string | null; language: string; children: ReactNode }) {
const [initial] = useState(() => restore(state)); // once, the same on the server and in the browser
const [squiddy, setSquiddy] = useState<Squiddy | null>(null);
useEffect(() => { // in the browser only, after hydration
const instance = initialize({ ...options, bundleId: "shop.example.com", language, initialState: state });
setSquiddy(instance);
return () => instance.close();
}, [state, language]);
return <SquiddyProvider squiddy={squiddy} initial={initial}>{children}</SquiddyProvider>;
}
The instance of the page is created in an effect, never while the client component renders: React renders client components on the server too, and an instance made there would be one more per request. restore is made once, with useState or useMemo, not at every rendering. Keep the server's module out of the client's code (the package server-only makes Next.js refuse it there). The SDK's Next.js sample is this, complete (the samples).
Remix (and React Router's framework mode). The loader serializes, the route component restores:
// app/routes/_index.tsx
import { useLoaderData } from "@remix-run/react"; // "react-router" in React Router 7
export async function loader() {
return { state: await squiddyState("en") }; // the module above, on the server
}
export default function Index() {
const { state } = useLoaderData<typeof loader>();
return (
<Providers state={state} language="en">
<Home />
</Providers>
);
}
Providers is the client component above, without "use client", which Remix does not need: its effect runs in the browser only there too. Keep squiddyState in a .server.ts module, which Remix leaves out of the browser's bundle.
Other frameworks follow the same three steps: an instance on the server, kept; the state in the page (a prop, a loader's data, a <script type="application/json">); restore for the first rendering and initialState for the page's instance.
Storage
The last configuration of each host, key and appId, and the installation id, are in the page's localStorage, under keys that start with cloud.squiddy.sdk/; the key itself is never stored. Every page of the same origin shares them, and clearing the site's data gives the browser a new installation id. Where the browser refuses localStorage, in a sandboxed frame or for a visitor who blocks the site's data, the SDK keeps them in memory for the life of the page and says so to the logger; a write the storage refuses, when it is full, is reported too, and the configuration is still served.
Calls and CORS
The SDK calls the data plane with the browser's fetch, from the page's origin, so through the browser's CORS checks, which Squiddy's data plane answers for every origin with no setting:
- the key travels in
X-API-Key, and the SDK's name and version inX-User-Agent(a page cannot setUser-Agent). No cookie is sent: the data plane takes none, and its answers allow no credentials; - the preflight costs nothing: the browser sends one before the first call, answered without the key and not counted against the key's limit, and reuses its answer for up to two hours;
- a Squiddy the browser cannot read is a
networkerror: a proxy in front of Squiddy that drops the CORS headers, or answers an error page without them, leaves the SDK nothing to read, so the state isfailedwithnetworkand the stored configuration.
The data plane is the only part of Squiddy that answers another origin: the dashboard and its services answer no CORS check, so a page elsewhere can never act with the session of someone signed in to Squiddy.
Errors
A failed check is a failed state whose error has a kind, a message, retryAfterSeconds (for rate_limited, when Squiddy said how long) and exceptionCode (for server_error, when Squiddy sent one). The table of errors says what each one means:
kind | Error in the table |
|---|---|
unauthenticated | Unauthenticated |
app_not_published | AppNotPublished |
incomplete_configuration | IncompleteConfiguration |
invalid_request | InvalidRequest |
tenant_suspended | TenantSuspended |
rate_limited | RateLimited |
server_error | ServerError |
network | Network, and any answer the browser does not let the page read |
timeout | Timeout |
malformed_response | MalformedResponse |
const { error } = squiddy.config;
if (error?.kind === "tenant_suspended") tellSomeone();
if (error?.kind === "rate_limited") log(`Squiddy is called again in ${error.retryAfterSeconds ?? 0} s`);
The samples
The SDK's repository has two web samples, with the screen of the other samples: the state of the configuration with a button that checks now, the gate, a localized string, a language picker and the configuration's settings, read from the configuration squiddy-sample.
- A static page, with no framework: the package from npm, served unbundled through an import map or bundled with esbuild, with the key in a
squiddy.local.jsonthat git ignores. - A Next.js app (App Router), rendered on the server: an instance per language on the server, the visitor's language from
Accept-Language, the state serialized into the page, the hooks with the restored values, and the page's instance started from the state. The key is in a.env.localthat git ignores, which Next.js reads on the server.