--- title: Svelte SDK description: "CaptchaLa Svelte component and action: installation, props, SvelteKit, and verification flow." --- # Svelte SDK Official Svelte component and action for CaptchaLa CAPTCHA — published as [`@captcha-la/svelte`](https://www.npmjs.com/package/@captcha-la/svelte). Current version: **1.0.1**. - `` component and `use:captchala` action - Works with Svelte 4 and Svelte 5 (runes or legacy mode); no TypeScript preprocessor needed - SSR safe in SvelteKit: nothing runs on the server - Loads the web SDK from our CDN at runtime ## Install ```bash npm install @captcha-la/svelte # or yarn add @captcha-la/svelte # or pnpm add @captcha-la/svelte ``` ## Quick start ### Component ```svelte console.error(err)} /> ``` Callback props work in Svelte 4 and 5. In Svelte 4 you can also listen with `on:success`, `on:error`, `on:close` and `on:ready` (the payload is in `event.detail`). ### Action The action mounts the widget into an element, or in bind mode binds it to the element it is used on, for example your own submit button: ```svelte
``` ## Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `appKey` | `string` | *required* | CaptchaLa application key | | `serverToken` | `string` | - | One-time, server-issued challenge token. Required when the app has `server_token_required=true`. See [`serverToken` mode](#server-token) | | `product` | `'popup' \| 'float' \| 'embed' \| 'bind'` | `'popup'` | Display mode | | `action` | `string` | `'default'` | Action identifier (e.g. `login`, `register`, `checkout`) | | `lang` | `string` | browser language | Language code (`zh-CN`, `en`, `ja`, …); unset = the browser language. Changing it switches the language in place | | `theme` | `string \| object` | follows the system | Preset string or `{ custom: { brightness: 'light' \| 'dark' \| 'system', ... } }` (see [Web SDK options](../web-sdk#common-options)) | | `bindTo` | `string \| HTMLElement` | - | Element or selector to bind to (only for `product="bind"`) | | `onServerTokenExpired` | `() => Promise \| string \| null` | - | Called when `serverToken` is rejected; return a new token to retry once, or `null` to report the error | | `onSuccess` | `(result) => void` | - | Success callback; `result` = `{ token, type, action }` (also the `success` event) | | `onExpired` | `() => void` | - | Called once, instead of `onError`, when the pass token expires before it was used; the widget shows the expiry. See [Token expiry](#token-expiry) | | `onError` | `(error) => void` | - | Error callback (also the `error` event) | | `onClose` | `() => void` | - | Close callback (also the `close` event) | | `onReady` | `() => void` | - | Ready callback (also the `ready` event) | | `class` | `string` | - | Container class name | | `style` | `string` | - | Container inline styles | Changing `appKey`, `product`, `action`, `bindTo`, `serverToken` or `theme` rebuilds the widget. ## Methods (via `bind:this`) ```svelte ``` | Method | Description | |--------|-------------| | `verify()` | Trigger verification | | `reset()` | Reset CAPTCHA state | | `destroy()` | Destroy the instance | | `bind(selector)` | Bind to element (for `bind` mode). Named `bind` because `bindTo` is the prop | | `setLang(lang)` | Switch language in place | | `getInstance()` | The underlying web SDK instance | ## `use:captchala` action ```ts use:captchala={{ appKey, // string, required product, // 'popup' | 'float' | 'embed' | 'bind' action, lang, theme, serverToken, onServerTokenExpired, bindTo, // bind mode: defaults to the element the action is on onSuccess, onError, onClose, onReady, onExpired, onInit // (instance) => void: the SDK instance, for verify() / reset() }} ``` When the options change, the widget is rebuilt if `appKey`, `product`, `action`, `bindTo`, `serverToken` or `theme` changed (keep a `theme` object in a variable rather than writing it inline); a `lang` change switches the language in place; callbacks are always read fresh. ## Token expiry {#token-expiry} If the pass token runs out before the form uses it, the widget shows that the verification expired (in `bind` mode nothing is shown, since the button is yours) and `onExpired` fires once, instead of `onError`. Start a new verification with `reset()` then `verify()`, or show your own prompt. ```svelte { token = r.token; expired = false }} onExpired={() => { token = ''; expired = true }} /> {#if expired} {/if} ``` Expiry handling is switched on by the `onExpired` prop; the `expired` event is dispatched as well, but only when the prop is set. Without `onExpired`, `onError` fires once (class `expired`). `onExpired` never fires for offline or degraded tokens. The action's `onExpired` option works the same way. ## SvelteKit and SSR The package is SSR safe. During server rendering (and prerendering) the component outputs an empty container; the SDK is loaded only in the browser, from `onMount`. Actions never run on the server. No `browser` checks or `ssr = false` are needed. - Do not call `loadCaptchalaSDK()` at module top level in a `+page.js` / `+layout.js` load function that runs on the server; it rejects outside the browser. - Fetch the `serverToken` from your own `+server.js` endpoint in the browser, or return it from a server `load` function, so the app secret stays on the server. ## Production: `serverToken` mode {#server-token} For high-value flows (login, register, payment) we recommend the **server-issued token flow**. Your backend mints a one-time `server_token` (5-minute TTL) via `POST /v1/server/challenge/issue` and hands it to the browser: ```svelte {#if serverToken} console.log('pass_token:', r.token)} /> {:else}
Loading…
{/if} ``` Backend endpoint (SvelteKit, `src/routes/api/captcha-token/+server.js`): ```js import { json } from '@sveltejs/kit' import { env } from '$env/dynamic/private' export async function GET() { const r = await fetch('https://verify.captcha.la/v1/server/challenge/issue', { method: 'POST', headers: { 'X-App-Key': env.CAPTCHALA_APP_KEY, 'X-App-Secret': env.CAPTCHALA_APP_SECRET, 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'action=login&ttl=300' }) const { data } = await r.json() return json({ server_token: data.server_token }) } ``` - Never embed the app secret in browser code. In SvelteKit, read it from `$env/dynamic/private` or `$env/static/private`. - Each `server_token` can be used exactly once. Fetch a new one before every widget mount. - Apps with `server_token_required=false` can still use the public `appKey`-only flow. See [API Reference](/api-reference) for the full backend contract. ## Server-side validation Validate the token from `onSuccess` on your server, for example in a SvelteKit form action: ```js // src/routes/login/+page.server.js import { fail } from '@sveltejs/kit' import { env } from '$env/dynamic/private' export const actions = { default: async ({ request, getClientAddress }) => { const form = await request.formData() const response = await fetch('https://verify.captcha.la/v1/validate', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-App-Key': env.CAPTCHALA_APP_KEY, 'X-App-Secret': env.CAPTCHALA_APP_SECRET }, // client_ip is optional but recommended body: JSON.stringify({ pass_token: form.get('captcha_token'), client_ip: getClientAddress() }) }) const result = await response.json() if (!(result.code === 0 && result.data.valid === true)) { return fail(400, { captcha: 'invalid' }) } // Token is valid, proceed with the request } } ``` The [Node.js SDK](./server-node) wraps the same call (`captchala.validate(token, { clientIp })`) and also issues server tokens. ## TypeScript Type definitions are included: ```ts import { Captchala, captchala, type CaptchalaResult, type CaptchalaActionOptions, type CaptchalaInstance } from '@captcha-la/svelte' ``` ## Versions - **1.0.1** (2026-11-27): README in Japanese, Korean, Spanish, Portuguese (BR) and German; no code changes. - **1.0.0**: first public release. ## Links - [npm](https://www.npmjs.com/package/@captcha-la/svelte) · [GitHub](https://github.com/Captcha-La/svelte) - [Web SDK overview](/web-sdk) · [API Reference](/api-reference)