Skip to main content

Enable Cloudflare Turnstile

Add bot protection to the chat WebSocket connection using Cloudflare Turnstile.

1. Create a Turnstile widget

  1. Go to the Cloudflare dashboard → Turnstile
  2. Add a new site with your domain (e.g., cht.bio)
  3. Copy the Site Key and Secret Key

2. Configure the backend

Add to your .env:

CHATINBIO_TURNSTILE_SECRET_KEY=0x4AAAAAAA...
CHATINBIO_TURNSTILE_SITE_KEY=0x4AAAAAAA...

When CHATINBIO_TURNSTILE_SECRET_KEY is set, the WebSocket handler will verify the token on connection. Without it, Turnstile is disabled.

3. Frontend integration

The <turnstile-guard> component in the frontend automatically renders the Turnstile widget when a site key is provided via the /api/bio response. The token is passed as a query parameter when connecting to the WebSocket:

ws://localhost:8000/ws/chat?visitor_id=xxx&turnstile_token=yyy

How it works

  1. Before the first chat message, the frontend renders the Turnstile challenge
  2. On success, the token is included in the WebSocket connection URL
  3. The backend calls Cloudflare's siteverify API to validate the token
  4. If invalid, the connection is rejected with an error message