• Stars
    star
    137
  • Rank 261,006 (Top 6 %)
  • Language Svelte
  • License
    MIT License
  • Created almost 2 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A lightweight Svelte component for Cloudflare Turnstile

Svelte Turnstile

Works with Svelte 3 & 4!

Cloudflare's Turnstile is a new CAPTCHA alternative, this library allows you to easily integrate it into your svelte projects.

Installing

npm install svelte-turnstile -D

Demo

https://svelte-turnstile.pages.dev/

Using

The only required prop is the siteKey which you can get from adding a site here.

<script>
    import { Turnstile } from 'svelte-turnstile';
</script>

<Turnstile siteKey="SITE_KEY" />

Props

Prop Type Description Required
siteKey string sitekey for your website
theme 'light' | 'dark' | 'auto' colour theme of the widget (defaults to auto)
size 'normal' | 'compact' size of the widget (defaults to normal)
action string A string that can be used to differentiate widgets, returned on validation
cData string A string that can attach customer data to a challange, returned on validation
tabIndex number Used for accessibility (defaults to 0)
forms boolean if true the response token will be a property on the form data (default true)
formsField string the name of the input which will appear on the form data (default cf-turnstile-response)
retry 'auto' | 'never' should the widget automatically retry to obtain a token if it did not succeed (default auto)
retryInterval number if retry is true, this controls the time between attempts in milliseconds (default 8000)
language SupportedLanguage | 'auto' the language turnstile should use (default auto)
execution 'render' | 'execute' controls when to obtain the token of the widget (default render)
appearance 'always' | 'execute' | 'interaction-only' controls when the widget is visible. (default always)

For more information about some of the props and a list of SupportedLanguage's checkout the Cloudflare Documentation.

Events

Event Data Description
turnstile-error {} Emitted when a user fails verification
turnstile-expired {} Emitted when a challenge expires and does not reset the widget
turnstile-timeout {} Emitted when a challenge expires and does reset the widget
turnstile-callback { token: string } Emitted when a user passes a challenge

Validate CAPTCHA

We need to validate the captcha token server side before we do any action on the server, this is to ensure no forgery occured. We can create a simple validate function:

If you are using a HTML Form and POSTing to a server you can get the cf-turnstile-response (or what you configured it to using the formsField option) property to get the token, otherwise you can use the on:turnstile-callback event in svelte to keep track of the token and send it to your backend.

interface TokenValidateResponse {
    'error-codes': string[];
    success: boolean;
    action: string;
    cdata: string;
}

async function validateToken(token: string, secret: string) {
    const response = await fetch(
        'https://challenges.cloudflare.com/turnstile/v0/siteverify',
        {
            method: 'POST',
            headers: {
                'content-type': 'application/json',
            },
            body: JSON.stringify({
                response: token,
                secret: secret,
            }),
        },
    );

    const data: TokenValidateResponse = await response.json();

    return {
        // Return the status
        success: data.success,

        // Return the first error if it exists
        error: data['error-codes']?.length ? data['error-codes'][0] : null,
    };
}

SvelteKit Example

In SvelteKit we can use form actions to easily setup a form with a captcha:

routes/login/+page.svelte

<script>
    import { Turnstile } from 'svelte-turnstile';

    /** @type {import('./$types').ActionData} */
    export let form;
</script>

{#if form?.error}
    <p>{form?.error}</p>
{/if}

<form method="POST" action="/login">
    <Turnstile siteKey="SITE_KEY" theme="dark" />
</form>

routes/login/+page.server.js

// Copy and paste the validateToken function from above here

export const actions = {
    default: async ({ request }) => {
        const data = await request.formData();

        const token = data.get('cf-turnstile-response') // if you edited the formsField option change this
        const SECRET_KEY = '...' // you should use $env module for secrets

        const { success, error } = await validateToken(token, SECRET_KEY);

        if (!success)
            return {
                error: error || 'Invalid CAPTCHA',
            };

        // do something, the captcha is valid!
    }
}

Resetting

If you need to manually reset the widget, you can do so by binding to the reset prop. For example:

<script lang="ts">
    let reset: () => void | undefined;
</script>

<button on:click={() => reset?.()}>
    Reset
</button>

<Turnstile bind:reset />

Support

More Repositories

1

svelte-copy

A svelte action to copy text on click!
TypeScript
148
star
2

svelte-hamburgers

Custom Hamburger Icons in Svelte with ease
SCSS
72
star
3

svelte-body

Apply styles to the body in routes! Designed to work with Svelte Kit and Routify
TypeScript
60
star
4

rollup-obfuscator

A plugin to obfuscate javascript for rollup based on https://www.npmjs.com/javascript-obfuscator
TypeScript
34
star
5

sveltekit-basic-auth

TypeScript
23
star
6

jellycommands

A command handler for Discord.js
TypeScript
16
star
7

sourcebin

Fast and simple package to get and create bins from https://sourceb.in/
TypeScript
11
star
8

website

The repository for my website: ghostdev.xyz
Svelte
10
star
9

svelte-reduced-motion

A collection of utilities for working with reduced motion in svelte!
TypeScript
9
star
10

svelte-mount

A library to make detecting mounted state easier in Svelte
TypeScript
9
star
11

greset

A opinionated css reset based on the most popular resets to date
SCSS
9
star
12

neru

Neru is a small and lightweight file router for your favourite backends
TypeScript
9
star
13

ghostsui

My personalised UI library
Svelte
7
star
14

djs-ticketsystem

DJS-TicketSystem is an extension to discord.js designed to make creating "tickets" in discord servers easier
JavaScript
7
star
15

sass-hex-rgb

A util for converting hex values to rgb (e.g. #302def -> 48, 45, 239)
SCSS
5
star
16

extractinator

TypeScript
5
star
17

tauri-file-reader

Svelte
5
star
18

shire

Shire is a simple no fuss ddns client for cloudflare
Rust
4
star
19

tauri-sveltekit

A simple Tauri SvelteKit template
HTML
4
star
20

short

A microservice for creating short links
Svelte
4
star
21

create-ghost

JavaScript
4
star
22

github1s-button

This is a simple extension that makes it easy to jump back and forth between github1s and github.
JavaScript
4
star
23

cloudflare-pages-cleanup

TypeScript
4
star
24

MyKV

MyKV is a SQL Key - Value wrapper with some extra features.
TypeScript
4
star
25

dashargs

Simple package for parsing command line style arguments
JavaScript
4
star
26

tst

TypeScript
3
star
27

mnemonic-worker

A cloudflare worker for generating mnemonic phrases
Rust
3
star
28

cc-carl

Lua
3
star
29

svelte-kit-theme-switcher-demo

Svelte
2
star
30

backblaze-cli

A simple backblaze cli
TypeScript
2
star
31

svite-3d

Svelte
2
star
32

svelte-sirens-routify-2021

Slidev for my Talk: Exploring Routify in SvelteKit
CSS
2
star
33

linode-object-upload

A simple cli tool to upload a file to Linode Object Storage
JavaScript
2
star
34

svelte-copy-require-repro

svelte-copy seems to fail with require on sveltekit netlify
JavaScript
2
star
35

s3-client

Svelte
2
star
36

pog-pog-repl

https://repl.willow.sh
Svelte
2
star
37

tauri-code-viewer

a testing app I made while exploring tauri
Svelte
2
star
38

listmonk-tweaked

Go
2
star
39

svelte-postcss-template

A svelte & postcss template
JavaScript
1
star
40

ghoststools

A collection of common functions I use
JavaScript
1
star
41

time

Time tracking apps
Svelte
1
star
42

svelte-logo-3d

Svelte
1
star
43

tasks

Svelte
1
star
44

search

TypeScript
1
star
45

esm.sh-extension

TypeScript
1
star
46

mega-space-train

TypeScript
1
star
47

willow.sh

TypeScript
1
star
48

dotfiles

My configs
Shell
1
star
49

gnome-shell-extension-gitpod

TypeScript
1
star
50

rpilocator-webhooks

TypeScript
1
star
51

netlify-sveltekit-esm-only-broke

JavaScript
1
star
52

cc-glib

A standard set of libraries/tools for CC Tweaked
Lua
1
star
53

imagine

TypeScript
1
star
54

svelte-kit-package-no-router

An example of how you can use svelte kit package without a router
JavaScript
1
star
55

default-export-poc

TypeScript
1
star
56

linode-bucket-delete

A cli tool to help you upload to delete a linode object storage bucket
JavaScript
1
star
57

pomadoro-bot

JavaScript
1
star
58

cf-pages-basic-auth

TypeScript
1
star
59

svelte-scss-template

Implements svelte, scss, and postcss (for autoprefixer)
JavaScript
1
star
60

svelte-london-pocketbase-talk

1
star
61

sveltekit-pages-stripe-test

JavaScript
1
star
62

quacko

TypeScript
1
star
63

routify-email-repro

CSS
1
star
64

kjua-revived

TypeScript
1
star
65

request-bin

Simple request bin built on Cloudflare Workers
TypeScript
1
star
66

bereal-rs

Rust
1
star