The client
Load the script and place the check. It runs, shows itself when it needs the visitor, and puts a single-use token in your form.
Load the script
<script src="https://hc.acecaptcha.com/v1/client.js" defer></script>The script sets the global window.AceCaptcha. Load it on every page that runs the check. An npm package is coming; until then, the script tag is the way in, and the TypeScript declarations below cover its API.
Add the check to a form
<script src="https://hc.acecaptcha.com/v1/client.js" defer></script><form action="/login" method="post"> <input name="email" type="email" autocomplete="username" required> <input name="password" type="password" autocomplete="current-password" required> <div class="ace-captcha" data-sitekey="ace_site_xxxxxxxxxxxxxxxxxxxxxx" data-action="login" ></div> <button>Sign in</button></form>That’s the whole page side. The check takes no space until it’s needed, and:
- it starts when the visitor first uses the form, and the submit waits for it;
- the form is sent with a token in
ace-token, a new one for every submit; - if it isn’t sure, it shows the visible check right there, and sends the form once that’s solved;
- if it can’t run, it says why and offers “Try again”.
Submit with a button or form.requestSubmit(). form.submit() skips every submit handler, the check’s included.
When it runs
focusDefault in a form- When the visitor first uses the form, so the token is usually ready by the submit.
loadDefault elsewhere- As soon as the page is ready. For pages that do something right away, like preparing a download.
submit- On the submit, or when you call
getToken(). Runs the fewest checks.
Every run counts as one check, so on busy pages without a form pick submit where you can. A token that gets too old is replaced when it’s needed, never in the background.
From JavaScript
const ace = AceCaptcha.create({ sitekey: 'ace_site_xxxxxxxxxxxxxxxxxxxxxx' })const check = ace.render('#check', { action: 'download', theme: 'dark', onToken: (token) => startDownload(token), // sends it to your backend})render puts the same check on an element you name, in or outside a form. A form takes one check.
Options
actiondata-action- What the check is for, like
loginorcheckout. See actions. rundata-runload,focusorsubmit. See when it runs.themedata-themelight,darkorauto, the default, which follows what your page paints behind the check.onTokendata-callback- Called with each new token. The attribute takes the name of a global function.
onErrordata-error-callback- Called with the code of a check that couldn’t run.
fieldNamedata-field-name- The hidden field’s name in a form. Default
ace-token. colorsbg,fgandaccentas#rrggbb, each on top of the theme.texts- Any of the check’s words, in your page’s language. See theme and words.
progressfalsehides the “Checking your browser…” line, for pages with a loading state of their own.onStatus- Reports what the visible check is doing, from
'shown'on. timeoutMs- How long one check may take. Default
30000; the clock pauses while the tab is hidden.
Attributes also work outside a form. The script renders the elements that are there when the page loads; for ones added later, call render.
<div class="ace-captcha" data-sitekey="ace_site_xxxxxxxxxxxxxxxxxxxxxx" data-action="download" data-theme="dark" data-callback="startDownload"></div><script> function startDownload(token) { // Send the token to your backend. }</script>Getting tokens yourself
const check = ace.render('#check', { action: 'comment', run: 'submit' })button.addEventListener('click', async () => { const token = await check.getToken() // a new one every time await fetch('/api/comments', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text: input.value, token }), })})getToken()resolves with a token nobody got before, from a new check if there’s none ready. It rejects with a code when the check can’t run.- Outside a form, a token passed to
onTokenis yours to send, andgetToken()won’t return it again. remove()takes the check off the page.
When your backend refuses
The decision is only known to your backend. When it refuses, answer with something your page recognizes, like a status of its own, and tell the check:
const reply = await fetch('/login', { method: 'POST', body: new FormData(form) })if (reply.status === 403) { // Your backend refused the check: says so and offers "Try again". AceCaptcha.get('.ace-captcha').reset({ refused: true })}“Try again” runs a new check and sends the form again, or calls onToken outside a form. Without refused, reset() drops the token and a waiting submit; a check that runs on load then runs again.
The visible check
When a check isn’t clean, AceCaptcha can ask the visitor for one short task inside your page. Most visitors never see it. A solved check earns allow. Repeated failures earn block. A visitor who recently solved it skips it for a while.
When it shows
It can appear only when your site is in enforce mode and its plan includes the visible check, and it appears only when a check isn’t clean. In shadow mode nobody sees it.
Theme and words
ace.render('#check', { action: 'signup', theme: 'dark', colors: { accent: '#ff5c3d' }, // bg, fg and accent, each optional texts: { title: 'Halte den Ring mit der Lücke', guide: 'Folge ihm, wenn er sich bewegt. Lass los, wenn er voll ist.', tryAgain: 'Nochmal versuchen', },})The check is up to 362px wide and uses your page’s font. It comes in English; pass texts for any other language. The TypeScript declarations list every text. Your page’s styles don’t reach inside it.
Keyboard operation of the visible check is coming.
Run checks yourself
render is built on execute. Call it directly when you want your own interface around the check.
const ace = AceCaptcha.create({ sitekey: 'ace_site_xxxxxxxxxxxxxxxxxxxxxx' })ace.version // the client's version string- One client per page, created early. It counts interaction from the moment it’s created, so create it when the page loads, not when the visitor submits.
- Browser only.
createthrows outside a browser, so don’t call it during server-side rendering. destroy()removes the client’s frames and checks, and rejects any pendingexecutewithdestroyed.
Get a token with execute
const token = await ace.execute({ action: 'signup' })// Send the token to your backend with the form or request.Call execute at submit time, right before you send the form. It resolves with the token. Tokens work once and expire 5 minutes after they’re issued, so don’t fetch one early and keep it. Concurrent calls are fine; they queue.
| Option | Type | What it does |
|---|---|---|
action | string | What the check is for, like login, signup or checkout. See actions. |
timeoutMs | number | How long execute may take. Default 30000; the clock pauses while the tab is hidden. |
interactive | object | Where the visible check may appear, and how it looks. See your own container. |
Actions
An action names the form or step the token is for. It’s either empty or 1 to 32 characters from A–Z, a–z, 0–9, _ and -. With anything else, render throws and execute rejects.
Siteverify echoes the token’s action back. If your backend also sends the action it expects, a token issued for a different action fails with action-mismatch, so a token from your newsletter form can’t be replayed against your login. Use one action per form.
Your own container for the visible check
With execute, the visible check appears in the container you pass, and the words around it are yours.
const box = document.getElementById('ace-check') // empty, and hidden until neededtry { const token = await ace.execute({ action: 'checkout', timeoutMs: 30000, interactive: { container: box, label: 'Security check', colors: { bg: '#ffffff', fg: '#1a1a2e', accent: '#2f6df6' }, onStatus(status) { if (status === 'shown') box.hidden = false }, }, }) // Send the token with the order.} finally { box.hidden = true}- It renders inside your container at full width, up to 360px wide, with an aspect ratio of 300:160. Keep the container empty, and reveal it when
onStatusreports'shown'. containercan be a function. It’s asked at the moment the check needs a place; returnnullto mean “not now”.labelis the accessible title of the check’s frame.colorstakesbg,fgandaccentas#rrggbb; set all three, or they’re ignored.- Without a container, no visible check is offered and the decision stands as issued:
allow_limitedstaysallow_limited.
Errors
A check that can’t run ends in a short code: onError gets it, and execute and getToken reject with an Error whose message is the code. A rendered check tells the visitor by itself. Some codes are retried automatically once before you see them.
Setup
invalid-sitekey- The sitekey isn’t a valid AceCaptcha sitekey. Check the value you passed to create.
invalid-action- The
actionisn’t empty and isn’t 1–32 letters, digits,_or-. origin-not-allowed- The page’s hostname isn’t listed on the site.
Loading
frame-timeout-*- The check’s frame didn’t load. Usually a Content Security Policy blocking it, a hostname missing from the site, or a blocker extension.
core-unavailablecore-timeoutcore-load- The client couldn’t load. Retry later.
Running
timeout- The check didn’t finish within
timeoutMs. widget-timeout- The visible check didn’t load in time.
no-container- The visible check was needed and there was no container to show it in.
rate-limited- Too many requests. Retry later.
destroyeddestroy()orremove()was called while the check was running.
With execute, let the visitor retry: show a short message and keep the form as it was. For critical flows, decide per action whether a failure here lets the request through (fail open) or stops it (fail closed).
try { form.elements['ace-token'].value = await ace.execute({ action: 'login' }) form.submit()} catch (error) { console.warn('AceCaptcha:', error.message) // e.g. 'timeout', 'origin-not-allowed' document.getElementById('login-error').textContent = 'We couldn’t check this request. Please try again.'}Content blockers
The client needs scripts and a frame from hc.acecaptcha.com. Some filter lists block every third-party request of a kind on a few sites, whatever it’s for. If they block fetches on yours, the client works around it. If they block third-party scripts or frames, the check can’t run: it ends in core-* or frame-timeout-*, or the script itself doesn’t load and window.AceCaptcha is missing.
Single-page apps
Create a single client at the app root, as a module-level value, and reuse it everywhere. Don’t create one per component or per route. Use render here instead of the ace-captcha class, which belongs to pages your framework doesn’t re-render.
// ace.ts: one client for the whole app.let client: AceCaptchaClient | null = null/** Call once at the app root, in the browser. Not during server rendering. */export function startAce(): AceCaptchaClient { client ??= AceCaptcha.create({ sitekey: 'ace_site_xxxxxxxxxxxxxxxxxxxxxx' }) return client}/** Use the same client everywhere. */export function getAce(): AceCaptchaClient { return client ?? startAce()}Create it in the browser, as soon as the app runs there: with server rendering, that’s an effect at the root. Remove a check when its component unmounts.
import { useEffect, useRef, type FormEvent } from 'react'import { getAce } from './ace'/** Put it in a form: the submit waits for the check, and the token goes along as ace-token. */export function AceCheck({ action, checkRef }: { action: string; checkRef?: { current: AceCaptchaCheck | null } }) { const box = useRef<HTMLDivElement>(null) useEffect(() => { const check = getAce().render(box.current!, { action }) if (checkRef) checkRef.current = check return () => check.remove() }, [action, checkRef]) return <div ref={box} />}export function SignupForm() { const check = useRef<AceCaptchaCheck | null>(null) async function onSubmit(event: FormEvent<HTMLFormElement>) { event.preventDefault() const reply = await fetch('/api/signup', { method: 'POST', body: new FormData(event.currentTarget) }) if (reply.status === 403) check.current?.reset({ refused: true }) } return ( <form onSubmit={onSubmit}> <input name="email" type="email" required /> <AceCheck action="signup" checkRef={check} /> <button>Create account</button> </form> )}TypeScript
Until the npm package ships, declare the global yourself. This file covers the whole client API.
// acecaptcha.d.ts: types for the script-tag client.interface AceCaptchaClient { readonly version: string /** Puts a check on the page. */ render(target: string | HTMLElement, options?: AceCaptchaRenderOptions): AceCaptchaCheck /** Resolves with a single-use token. */ execute(options?: AceCaptchaExecuteOptions): Promise<string> destroy(): void}interface AceCaptchaCheck { /** A token that wasn’t handed out before, from a new check if there’s none. */ getToken(): Promise<string> /** Drops the token; run: 'load' runs again. refused: your backend said no, so the visitor can try again. */ reset(options?: { refused?: boolean }): void remove(): void}interface AceCaptchaRenderOptions { /** '' or 1–32 of A–Z a–z 0–9 _ - */ action?: string /** 'focus' in a form, else 'load'. */ run?: 'load' | 'focus' | 'submit' /** Default 'auto': follows the page behind the check. */ theme?: 'auto' | 'light' | 'dark' colors?: { bg?: string; fg?: string; accent?: string } texts?: Partial<Record<AceCaptchaText, string>> /** The hidden field in a form. Default 'ace-token'. */ fieldName?: string /** Default true: a check the visitor waits for says that it’s running. */ progress?: boolean timeoutMs?: number onToken?(token: string): void onError?(code: string): void onStatus?(status: AceCaptchaWidgetStatus): void}interface AceCaptchaExecuteOptions { /** '' or 1–32 of A–Z a–z 0–9 _ - */ action?: string /** Default 30000; paused while the tab is hidden. */ timeoutMs?: number /** Where the visible check may appear. */ interactive?: { container: HTMLElement | (() => HTMLElement | null) label?: string colors?: { bg?: string; fg?: string; accent?: string } onStatus?(status: AceCaptchaWidgetStatus): void }}type AceCaptchaWidgetStatus = | 'shown' | 'idle' | 'holding' | 'filled' | 'miss' | 'early' | 'slip' | 'held' | 'solved' | 'failed' | 'sending' | 'next' | 'retry'type AceCaptchaText = | 'checking' | 'title' | 'guide' | 'label' | 'miss' | 'early' | 'slip' | 'filled' | 'held' | 'wait' | 'next' | 'retry' | 'tryAgain' | 'refused' | 'failed' | 'slow' | 'blocked' | 'unsupported' | 'rateLimited' | 'setup'declare var AceCaptcha: { create(options: { sitekey: string }): AceCaptchaClient /** The check on an element. */ get(target: string | HTMLElement): AceCaptchaCheck | undefined}Content Security Policy
If your page sends a Content Security Policy, add AceCaptcha to these directives:
script-src 'self' https://hc.acecaptcha.com 'wasm-unsafe-eval';frame-src https://hc.acecaptcha.com;connect-src 'self' https://hc.acecaptcha.com;Note
The page must be served over https, from a hostname listed on the site. Plain http is never allowed for customer sites. A missing hostname shows up as origin-not-allowed or a frame-timeout-* error. To develop on localhost, use the test keys.