Cloudflare Turnstile Server-Side Verification (Node.js)

'use strict'; /** * Validates Cloudflare Turnstile CAPTCHA response token * @param {string} token - The cf-turnstile-response string from form body * @param {string} remoteIp - Optional remote client IP address * @returns {Promise<{ success: boolean, errorCodes?: string[] }>} */ async function verifyTurnstileToken(token, remoteIp = null) { const secretKey = process.env.TURNSTILE_SECRET_KEY; if (!secretKey) { throw new Error('TURNSTILE_SECRET_KEY is not configured in environment'); } if (!token || typeof token !== 'string') { return { success: false, errorCodes: ['missing-input-response'] }; } const formData = new URLSearchParams(); formData.append('secret', secretKey); formData.append('response', token); if (remoteIp) { formData.append('remoteip', remoteIp); } const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 5000); try { const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { method: 'POST', body: formData, signal: controller.signal, }); const result = await res.json(); return { success: Boolean(result.success), errorCodes: result['error-codes'] || [], }; } catch (err) { return { success: false, errorCodes: [err.name === 'AbortError' ? 'timeout' : 'network-error'] }; } finally { clearTimeout(timeoutId); } } module.exports = { verifyTurnstileToken };
Cloudflare Turnstile Server-Side Verification (Node.js)
Note
Notification