--- title: Node.js Server SDK description: "Verify CaptchaLa tokens from Node.js: official server SDK installation and usage, with Express, Next.js and Fastify helpers." --- # Node.js Server SDK Official Node.js server-side SDK, published as [`@captcha-la/node`](https://www.npmjs.com/package/@captcha-la/node) on npm. Written in TypeScript, zero runtime dependencies, ESM and CommonJS. Three jobs the SDK handles for you: 1. **Validate**: verify a `pt_` pass token from the browser or native SDK. 2. **Issue**: mint a one-time `sct_` server token to bind the upcoming challenge to a specific action / IP / user. 3. **Moderate**: multi-modal (text + image) content moderation. ## Install ```bash npm install @captcha-la/node ``` Requires **Node.js 18+** (uses the global `fetch`). ## Validate (`pt_` token) Pass the end-user's IP as `clientIp`. Optional, but **recommended**: it's used for additional risk checks. ```ts import { CaptchaLaClient } from '@captcha-la/node'; // Reads CAPTCHALA_APP_KEY / CAPTCHALA_APP_SECRET when not passed. const captchala = new CaptchaLaClient({ appKey: 'your_app_key', appSecret: 'your_app_secret' }); const result = await captchala.validate(req.body.captcha_token, { clientIp: req.ip, expectedAction: 'login', // optional: action_mismatch otherwise expectedHostname: 'www.example.com', // optional: hostname_mismatch otherwise }); if (!result.valid) { return res.status(400).json({ error: result.error }); // e.g. "token_expired" } // Verification passed; proceed with the request. // result.captchaArgs has platform / userIp / referer / pkg / solvedAt / riskScore ``` `validate()` never throws for invalid tokens, API errors or network failures. Check `result.valid` and `result.error`. For API or network failures, `result.cause` holds a typed error (`NetworkError`, `TimeoutError`, `AuthenticationError`, `RateLimitError`, …). If you issued the original `server_token` with `bindUid`, compare the `uid` returned with the user you actually expect: ```ts if (result.uid !== expectedUserId) { return res.status(400).send('user mismatch'); } ``` You can also send the [end-user identity](/api-reference#identity) (`bindUid`, `bindAccount`, `bindEmail`, `bindPhone`, `scene`) to `validate()` and check `result.bindingMismatch`. ## Framework helpers Subpath exports, with no dependency on the framework. The token is read from the `captcha_token` / `captchala_token` body field or the `X-Captcha-Token` header. On failure they answer HTTP 400 `{"error":"captcha_failed","code":"…"}`. ```ts const client = new CaptchaLaClient(); // Express import { captchala } from '@captcha-la/node/express'; app.post('/login', express.json(), captchala({ client, expectedAction: 'login' }), handler); // req.captchala is the ValidateResult // Next.js App Router: app/api/login/route.ts import { withCaptchaLa } from '@captcha-la/node/next'; export const POST = withCaptchaLa({ client, expectedAction: 'login' }, async (req, ctx, captcha) => Response.json({ ok: true, uid: captcha.uid })); // Fastify import { captchalaPreHandler } from '@captcha-la/node/fastify'; fastify.post('/login', { preHandler: captchalaPreHandler({ client, expectedAction: 'login' }) }, handler); ``` ## Retries and timeouts `timeoutMs` (default 5000) applies per attempt; `maxRetries` (default 2) retries connection failures and HTTP 502 / 503 / 504 with exponential backoff. Rate-limit answers are not retried; see `result.retryAfter`. Moderation calls are not retried after a timeout. ## Client-only tokens (outage fallback) When the CaptchaLa API can't be reached, the client SDK can still finish the challenge and hand back a client-only token (prefix `client_` or `co_`). It is accepted only if the API is unreachable from your server as well; otherwise it is rejected with `error='client_only_rejected_api_reachable'`. An accepted token is marked `clientOnly=true`. The reachability result is cached (30 s when reachable, 5 s when not), and concurrent validations share a single check. For sensitive actions (login, payment) you can refuse client-only tokens even during an outage: ```ts const strict = new CaptchaLaClient({ rejectClientOnly: true }); // client_ / co_ -> valid=false, error='client_only_rejected_by_policy' ``` ## Issue a server token For high-value flows (login, register, payment) the recommended pattern is: the backend mints a one-time `sct_` token, hands it to the browser, and the browser passes it as the `serverToken` prop. ```ts const issue = await captchala.issueServerToken('login', { bindIp: req.ip, // optional; see the note on private relays in the API reference ttl: 300, // seconds; default 300 maxUses: 5, bindUid: user.id, // pair with result.uid on verify }); if (!issue.ok) { return res.status(503).json({ error: issue.error }); // rate_limit_exceeded, ... } res.json({ serverToken: issue.token }); // hand to browser ``` ## Moderate content ```ts import { textItem, imageUrlItem } from '@captcha-la/node'; const result = await captchala.moderationCheck( [textItem(userComment), imageUrlItem(uploadedImageUrl)], { userId: user.id }, ); if (!result.ok) { return { error: result.error }; } if (result.flagged && result.hasCategory('violence', 'csam')) { // hard block } // Plain-text shortcut const text = await captchala.moderationText('user comment here'); ``` Categories are model-defined; iterate `result.categories` defensively rather than hard-coding a fixed set. ## Testing Use the public [test keys](/api-reference#test-keys) to exercise your server's handling without solving a CAPTCHA. Results from them have `test === true`. In unit tests, pass a custom `fetch` to the client. ## Result types | Type | Fields | |---|---| | `ValidateResult` | `valid`, `error`, `message`, `action`, `uid`, `challengeId`, `hostname`, `challengeTs`, `riskLevel`, `riskLabels`, `captchaArgs`, `userIp`, `binding`, `bindingMatch`, `bindingMismatch`, `degraded`, `degradedReason`, `offline`, `clientOnly`, `warning`, `test`, `httpStatus`, `retryAfter`, `retryable`, `cause`, `raw`; `throwIfInvalid()`, `toJSON()` | | `IssueResult` | `ok`, `token`, `expiresIn`, `issuedAt`, `error`, `message`, `httpStatus`, `retryAfter`, `retryable`, `cause` | | `ModerationResult` | `ok`, `flagged`, `categories`, `categoryScores`, `contentType`, `raw`, `error`, `message`, `cause`; `hasCategory(...names)` | ## Links - [npm](https://www.npmjs.com/package/@captcha-la/node) · [GitHub](https://github.com/Captcha-La/captchala-node) - [Web SDK overview](/web-sdk) · [API Reference](/api-reference)