Svelte SDK
Official Svelte component and action for CaptchaLa CAPTCHA — published as @captcha-la/svelte. Current version: 1.0.1.
<Captchala>component anduse:captchalaaction- 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
npm install @captcha-la/svelte
# or
yarn add @captcha-la/svelte
# or
pnpm add @captcha-la/svelteQuick start
Component
<script>
import { Captchala } from '@captcha-la/svelte'
function handleSuccess(result) {
// Send result.token to your server for validation.
console.log('pass_token:', result.token)
}
</script>
<Captchala
appKey="your-app-key"
product="popup"
onSuccess={handleSuccess}
onError={(err) => 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:
<script>
import { captchala } from '@captcha-la/svelte'
let token = ''
</script>
<form method="POST">
<input type="email" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password" />
<input type="hidden" name="captcha_token" value={token} />
<button
type="button"
use:captchala={{
appKey: 'your-app-key',
product: 'bind',
action: 'login',
onSuccess: (result) => {
token = result.token
// Continue with form submission
}
}}
>
Login
</button>
</form>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 |
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) |
bindTo | string | HTMLElement | - | Element or selector to bind to (only for product="bind") |
onServerTokenExpired | () => Promise<string | null> | 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 |
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)
<script>
import { Captchala } from '@captcha-la/svelte'
let captcha
</script>
<Captchala bind:this={captcha} appKey="your-app-key" />
<button on:click={() => captcha.verify()}>Verify</button>| 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
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
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.
<script>
import { Captchala } from '@captcha-la/svelte'
let captcha
let token = ''
let expired = false
function verifyAgain() {
expired = false
captcha.reset()
captcha.verify()
}
</script>
<Captchala
bind:this={captcha}
appKey="your-app-key"
onSuccess={(r) => { token = r.token; expired = false }}
onExpired={() => { token = ''; expired = true }}
/>
{#if expired}
<button on:click={verifyAgain}>Verify again</button>
{/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.jsload function that runs on the server; it rejects outside the browser. - Fetch the
serverTokenfrom your own+server.jsendpoint in the browser, or return it from a serverloadfunction, so the app secret stays on the server.
Production: serverToken mode
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:
<script>
import { onMount } from 'svelte'
import { Captchala } from '@captcha-la/svelte'
let serverToken
onMount(async () => {
const r = await fetch('/api/captcha-token') // your own backend
serverToken = (await r.json()).server_token
})
</script>
{#if serverToken}
<Captchala
{serverToken}
appKey="pk_your_public_app_key"
action="login"
onSuccess={(r) => console.log('pass_token:', r.token)}
/>
{:else}
<div>Loading…</div>
{/if}Backend endpoint (SvelteKit, src/routes/api/captcha-token/+server.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/privateor$env/static/private. - Each
server_tokencan be used exactly once. Fetch a new one before every widget mount. - Apps with
server_token_required=falsecan still use the publicappKey-only flow.
See 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:
// 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 wraps the same call (captchala.validate(token, { clientIp })) and also issues server tokens.
TypeScript
Type definitions are included:
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.