@jscarle/vue3-turnstile
v1.1.1
Published
A Vue 3.5 TypeScript component for Cloudflare's Turnstile.
Downloads
332
Maintainers
Readme
vue3-turnstile
A Vue 3.5 TypeScript component for Cloudflare's Turnstile.
Requires Vue 3.5.17 or later and @unhead/vue 2.x (2.0.12+) or 3.x (3.1.0+).
Overview
vue3-turnstile wraps the Cloudflare Turnstile widget in a strongly typed Vue component. It exposes the Turnstile API methods as component methods and can be configured via component props or plugin defaults. Component props take precedence over plugin defaults.
Installation
npm install @jscarle/vue3-turnstileUsage
Component usage
<script setup lang="ts">
import { ref } from 'vue'
import { TurnstileWidget } from '@jscarle/vue3-turnstile'
const token = ref<string | null>(null)
</script>
<template>
<TurnstileWidget v-model="token" sitekey="your-site-key" />
</template>Registering globally
To make <TurnstileWidget /> available in all components:
import { createApp } from 'vue'
import App from './App.vue'
import { TurnstilePlugin } from '@jscarle/vue3-turnstile'
createApp(App).use(TurnstilePlugin).mount('#app')TurnstilePlugin installs the TurnstileWidget component globally and injects
default options for all widget props. Component props take priority over these
options, which therefore act as fallbacks for each <TurnstileWidget /> instance:
createApp(App).use(TurnstilePlugin, {
sitekey: 'your-site-key',
logLevel: 'debug',
})Customization
Global defaults passed to the plugin apply to every widget. Component props take precedence over these defaults, enabling per-instance configuration.
v-model is optional. Use it when you want the current token in local component
state, or use the success event directly when you only need to submit the token
to your server.
Test sitekeys
The library exports constants for Cloudflare's test sitekeys:
| Constant | Value | Description |
| --- | --- | --- |
| TEST_SITEKEY_ALWAYS_PASS | 1x00000000000000000000AA | Always passes (visible) |
| TEST_SITEKEY_ALWAYS_BLOCK | 2x00000000000000000000AB | Always blocks (visible) |
| TEST_SITEKEY_ALWAYS_PASS_INVISIBLE | 1x00000000000000000000BB | Always passes (invisible) |
| TEST_SITEKEY_ALWAYS_BLOCK_INVISIBLE | 2x00000000000000000000BB | Always blocks (invisible) |
| TEST_SITEKEY_CHALLENGE | 3x00000000000000000000FF | Forces an interactive challenge |
Component props
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| sitekey | string | - | Cloudflare Turnstile site key |
| action | string | - | Widget analytics action name |
| cData | string | - | Custom payload returned on validation |
| logLevel | 'debug' \| 'info' \| 'warn' \| 'error' | info | Browser log level |
| language | Language | auto | Widget language. Regional codes use Cloudflare's lower-case format, such as en-us or pt-br |
| theme | 'auto' \| 'light' \| 'dark' | auto | Widget theme |
| tabindex | number | 0 | iframe tabindex |
| size | 'normal' \| 'compact' \| 'flexible' | normal | Widget size |
| retry | 'never' \| 'auto' | auto | Automatically retry on failure |
| retry-interval | number | 8000 | Milliseconds between retries |
| appearance | 'always' \| 'execute' \| 'interaction-only' | always | When the widget is visible |
| response-field | boolean | true | Create a hidden form field containing the token |
| response-field-name | string | cf-turnstile-response | Hidden token field name |
| refresh-expired | 'never' \| 'manual' \| 'auto' | auto | Refresh behavior when token expires |
| refresh-timeout | 'never' \| 'manual' \| 'auto' | auto | Refresh behavior on timeout |
| execution | 'render' \| 'execute' | render | When to obtain the widget token |
| feedback-enabled | boolean | true | Allow Cloudflare feedback |
| offlabel-show-privacy | boolean | true | Show the privacy link for unbranded Turnstile widgets |
Events
The component emits the following events:
success(response: string)– emitted when the visitor solves the challenge. The returned token is also available viav-modeland should be sent to Cloudflare for verification.error(error: string)– emitted when a runtime error occurs while obtaining a token.expired– emitted when the token is no longer valid but the widget has not been reset.unsupported– emitted if the visitor's browser is unsupported by Cloudflare Turnstile.timeout– emitted when the interactive challenge was not solved in time.failed(error: unknown)– emitted if loading the widget fails entirely.
Use these events to react to the widget state and handle failures gracefully.
<script setup lang="ts">
function onSolved(token: string) {
// send token to your server
}
function onError(message: string) {
console.error(message)
}
</script>
<template>
<TurnstileWidget
sitekey="your-site-key"
@success="onSolved"
@error="onError"
@expired="() => console.log('expired')"
@timeout="() => console.log('timeout')"
@failed="err => console.error('load failed', err)"
/>
</template>Component methods
Template refs expose the following methods:
| Method | Description |
| --- | --- |
| render() | Render the widget manually |
| execute() | Execute the widget when execution is execute |
| reset() | Reset the current widget |
| remove() | Remove the current widget from the DOM |
Token Verification
Validate the response token on your server by sending it to Cloudflare's siteverify endpoint:
async function validateTurnstileToken(token: string) {
const formData = new FormData()
formData.append('secret', 'your-secret-key')
formData.append('response', token)
const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
method: 'POST',
body: formData,
})
return response.json() as Promise<{ success: boolean; 'error-codes'?: string[] }>
}Server-side validation is required. Tokens must be validated within 300 seconds and cannot be reused.
FAQ
Why do I see browser console warnings from challenges.cloudflare.com?
Cloudflare's Turnstile script is injected from https://challenges.cloudflare.com and
manages its own lifecycle inside an iframe. When it initializes, browsers may log
messages such as:
[Violation] 'readystatechange' handler took XXXmsAvoid using document.write()Request for the Private Access Token challenge.Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
These notices come directly from Cloudflare's challenge code and are not emitted by the
Vue component. They typically indicate performance or Content Security Policy details of
the third-party widget rather than problems in your application. If you want to reduce
the CSP warning, add an explicit script-src directive that includes
https://challenges.cloudflare.com so the browser does not fall back to default-src.
Contributing
Issues and pull requests are welcome. Feel free to open a ticket if you discover an issue or have a feature request.
License
This project is licensed under the MIT License.
