
SKILL LEVEL: Intermediate.
Many small nonprofits and law firms run their websites on a static host such as GitHub Pages or Netlify, often built with Hugo. Static sites are cheap, fast and hard to break, but they can’t send email on their own. A common fix is a contact form that posts to a Google Apps Script web app, which emails each submission to the team. It’s free and it works, until the spam starts.
In this article we’ll add Cloudflare Turnstile, Cloudflare’s free bot check, to that kind of form. The token gets verified inside Apps Script, the page shows a proper confirmation instead of a bare script page, and a setup mistake can’t quietly throw away a real enquiry.
example.org, <SITE_KEY> and <DEPLOYMENT_ID> with your own values. You need a free Cloudflare account. Your website does not have to be hosted on Cloudflare to use Turnstile.Tested on Ubuntu 24.04, curl 8.5 and jq 1.7 (Cloudflare Siteverify test keys), December 2026. The browser and Apps Script steps were checked against Cloudflare’s Turnstile documentation and Google’s Apps Script documentation.
What we’re building
- A Turnstile widget in Managed mode on your contact form, plus a hidden honeypot field.
- A small script that sends the form with
fetch()and shows the result on the page. - An Apps Script handler that checks the token with Cloudflare, emails only the fields you expect, and replies in JSON.
- A clear policy for what happens when the check fails.
Understand why the form attracts spam
A static-site form usually looks like <form action="https://script.google.com/macros/s/.../exec" method="post">. That URL sits in your page source, and the web app is deployed so that anyone can call it. A bot doesn’t need your form at all. It can post straight to the URL, and the script emails whatever it receives.
Two quieter problems tend to come with this setup:
- Visitors land on a bare script page. After a normal form post, the browser leaves your site and shows whatever the script returned, often a blank page or plain text on a Google domain. Some people assume the form broke and send their message again, or give up.
- Notifications can bounce without anyone noticing. The script sends email from the Google account that owns it, so bounce notices go to that account’s inbox. If the destination address was mistyped or later deleted, enquiries can fail for months while the owner’s inbox fills with “Address not found” messages that nobody reads.
Turnstile fixes the spam, fetch() fixes the bare page, and the end-to-end test at the end of this article catches the bounces.
Create a Turnstile widget
- Sign in to the Cloudflare dashboard and open Turnstile.
- Select Add widget.
- Give it a name you’ll recognize, such as “Website contact form”.
- Under Hostname management, add each domain the form runs on, for example
example.organdwww.example.org. - Set Widget mode to Managed. Cloudflare’s docs recommend it: most visitors pass without doing anything, and the rest are asked to tick a box. There are no puzzles or images to decode.
- Select Create, then copy the site key and the secret key.
The site key is public and belongs in your web page. The secret key is what lets your script ask Cloudflare whether a token is genuine, so it must never appear in page source, in the script’s code or in your Git repository. Cloudflare’s free plan currently covers up to 20 widgets with 10 hostnames each (plans).
Store the secret key in Script Properties
Apps Script has a built-in key-value store for settings like this, so the secret never sits in the code:
- Open your Apps Script project.
- Click Project Settings (the gear icon) on the left.
- Scroll to Script Properties and click Add script property.
- Set Property to
TURNSTILE_SECRETand Value to the secret key, then click Save script properties.
Anyone with edit access to the script project can still see this value. Keep the editor list short.
Add the widget and a honeypot to the form
Here’s the form markup. It uses Turnstile’s explicit rendering, which gives us a widget ID so the script can clear the widget after each submission (client-side rendering docs).
<form id="contact-form" action="https://script.google.com/macros/s/<DEPLOYMENT_ID>/exec" method="post">
<label for="cf-name">Name</label>
<input id="cf-name" name="name" required>
<label for="cf-email">Email</label>
<input id="cf-email" name="email" type="email" required>
<label for="cf-organization">Organization</label>
<input id="cf-organization" name="organization">
<label for="cf-message">Message</label>
<textarea id="cf-message" name="message" rows="6" required></textarea>
<!-- Honeypot: hidden from people, tempting to simple bots. -->
<div aria-hidden="true" style="position:absolute; left:-10000px;">
<label for="cf-website">Leave this field empty</label>
<input id="cf-website" name="website" tabindex="-1" autocomplete="off">
</div>
<div id="turnstile-widget" data-sitekey="<SITE_KEY>"></div>
<button type="submit">Send message</button>
<p id="form-status" role="status" aria-live="polite"></p>
</form>
<script src="/js/contact-form.js" defer></script>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onTurnstileLoad" defer></script>The honeypot is optional. People never see the field, but simple bots fill in every input they find. It’s a cheap first filter, and Turnstile does the real work.
Load api.js straight from challenges.cloudflare.com. Cloudflare warns that proxying or caching a copy of the file will break when they update it.
On a Hugo site, keep the site key in your configuration rather than in the template. Add it under [params] in hugo.toml (some themes keep params in config/_default/params.toml instead):
[params]
turnstile_sitekey = "<SITE_KEY>"Then change the widget line in your form template to:
<div id="turnstile-widget" data-sitekey="{{ site.Params.turnstile_sitekey }}"></div>Submit with fetch() and show the result on the page
Save this as static/js/contact-form.js in a Hugo site, or wherever your site keeps scripts. It renders the widget, sends the form in the background with format=json, shows a message under the button and then clears the widget for the next attempt. Turnstile tokens expire after five minutes and can be used only once, so every attempt needs a fresh one.
let turnstileWidgetId;
// Called by Turnstile's api.js once it has loaded (see onload= in the script tag).
function onTurnstileLoad() {
const box = document.getElementById('turnstile-widget');
turnstileWidgetId = turnstile.render('#turnstile-widget', { sitekey: box.dataset.sitekey });
}
document.getElementById('contact-form').addEventListener('submit', async function (event) {
event.preventDefault();
const form = event.currentTarget;
const status = document.getElementById('form-status');
const button = form.querySelector('button[type="submit"]');
const token = window.turnstile ? turnstile.getResponse(turnstileWidgetId) : '';
if (!token) {
status.textContent = 'Please complete the security check above, then send again.';
return;
}
const data = new URLSearchParams(new FormData(form));
data.set('cf-turnstile-response', token);
data.set('format', 'json');
button.disabled = true;
status.textContent = 'Sending...';
try {
const response = await fetch(form.action, { method: 'POST', body: data });
const result = await response.json();
if (result.ok) {
form.reset();
status.textContent = 'Thank you. Your message has been sent and we will reply soon.';
} else if (result.error === 'verification') {
status.textContent = 'We could not verify your message. Please complete the check again and resend.';
} else {
status.textContent = 'Sorry, your message could not be sent. Please email [email protected] instead';
}
} catch (err) {
status.textContent = 'Sorry, something went wrong. Please email [email protected] instead';
} finally {
button.disabled = false;
turnstile.reset(turnstileWidgetId);
}
});Sending a URLSearchParams body makes this a plain form-encoded POST, so Apps Script reads the fields from e.parameter exactly as it would for an ordinary form submission. Keep it that way: don’t add a Content-Type: application/json header or send a JSON body. That makes the browser send a CORS preflight request, which Apps Script doesn’t answer, and the page will show an error even when the message was sent.
Verify the token in Apps Script
Replace the contents of your script’s Code.gs with the code below and edit the settings block at the top. A few points to note:
doPosthands everything to one handler, anddoGetnever sends email.- The token goes to Cloudflare’s Siteverify endpoint from the script itself. Cloudflare is clear that the widget alone protects nothing: you must check the token on the server.
- The script checks
successand the returnedhostname, so a token solved on someone else’s site won’t be accepted. - Only the fields in
CONFIG.fieldsare emailed, and each is cut to a maximum length. Anything else a bot adds to the request is ignored.
// ==== Settings: edit these ====
const CONFIG = {
to: '[email protected]', // a mailbox or Google Group that really exists
subject: 'Website enquiry',
allowedHostnames: ['example.org', 'www.example.org'],
fields: ['name', 'email', 'organization', 'message'],
maxFieldLength: 5000,
siteUrl: 'https://example.org/contact/'
};
// ==== End of settings ====
const SITEVERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
function doPost(e) {
return handleSubmission_(e);
}
function doGet() {
// A GET request never sends anything.
return respond_({ ok: false, error: 'method' }, false);
}
function handleSubmission_(e) {
const p = (e && e.parameter) || {};
const wantsJson = p.format === 'json';
// Honeypot: people never see this field, so anything in it came from a bot.
if (p.website) {
console.log('Dropped: honeypot field was filled in.');
return respond_({ ok: true }, wantsJson);
}
const check = verifyTurnstile_(p['cf-turnstile-response']);
if (check.status === 'rejected') {
console.log('Rejected: ' + check.reason);
return respond_({ ok: false, error: 'verification' }, wantsJson);
}
const lines = CONFIG.fields.map(function (name) {
return name + ': ' + String(p[name] || '').slice(0, CONFIG.maxFieldLength);
});
let subject = CONFIG.subject;
if (check.status === 'unverified') {
subject = '[unverified] ' + subject;
lines.push('', 'Bot check not completed: ' + check.reason);
console.log('Sent unverified: ' + check.reason);
}
const message = { to: CONFIG.to, subject: subject, body: lines.join('\n') };
const email = String(p.email || '').trim();
if (/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
message.replyTo = email;
}
try {
MailApp.sendEmail(message);
} catch (err) {
console.error('MailApp failed: ' + err);
return respond_({ ok: false, error: 'send' }, wantsJson);
}
return respond_({ ok: true }, wantsJson);
}
// Returns { status: 'verified' | 'rejected' | 'unverified', reason }.
function verifyTurnstile_(token) {
if (!token) {
return { status: 'rejected', reason: 'no Turnstile token' };
}
if (token.length > 2048) {
return { status: 'rejected', reason: 'token too long' };
}
const secret = PropertiesService.getScriptProperties().getProperty('TURNSTILE_SECRET');
if (!secret) {
return { status: 'unverified', reason: 'TURNSTILE_SECRET is not set' };
}
let response;
try {
response = UrlFetchApp.fetch(SITEVERIFY_URL, {
method: 'post',
payload: { secret: secret, response: token },
muteHttpExceptions: true
});
} catch (err) {
return { status: 'unverified', reason: 'could not reach Cloudflare: ' + err };
}
if (response.getResponseCode() !== 200) {
return { status: 'unverified', reason: 'Cloudflare returned HTTP ' + response.getResponseCode() };
}
let result;
try {
result = JSON.parse(response.getContentText());
} catch (err) {
return { status: 'unverified', reason: 'unreadable reply from Cloudflare' };
}
if (result.success !== true) {
const codes = result['error-codes'] || [];
const ourProblem = ['missing-input-secret', 'invalid-input-secret', 'internal-error'];
const isOurs = codes.some(function (code) { return ourProblem.indexOf(code) !== -1; });
return {
status: isOurs ? 'unverified' : 'rejected',
reason: 'Cloudflare said: ' + (codes.join(', ') || 'no error code')
};
}
if (CONFIG.allowedHostnames.indexOf(result.hostname) === -1) {
return { status: 'rejected', reason: 'token was issued for ' + result.hostname };
}
return { status: 'verified', reason: '' };
}
function respond_(result, wantsJson) {
if (wantsJson) {
return ContentService.createTextOutput(JSON.stringify(result))
.setMimeType(ContentService.MimeType.JSON);
}
const text = result.ok
? 'Thank you. Your message has been sent.'
: 'Sorry, your message could not be sent. Please go back and try again.';
return HtmlService.createHtmlOutput(
'<p>' + text + '</p><p><a href="' + CONFIG.siteUrl + '" target="_top">Back to the website</a></p>'
);
}
// Run this once from the editor after adding UrlFetchApp (see the next sections).
function checkSetup() {
const secret = PropertiesService.getScriptProperties().getProperty('TURNSTILE_SECRET');
console.log('TURNSTILE_SECRET is ' + (secret ? 'set' : 'NOT set'));
const response = UrlFetchApp.fetch(SITEVERIFY_URL, {
method: 'post',
payload: { secret: secret || 'not-set', response: 'XXXX.DUMMY.TOKEN.XXXX' },
muteHttpExceptions: true
});
console.log('Cloudflare replied: ' + response.getContentText());
}Apps Script can’t see the visitor’s IP address, so the optional remoteip field that Siteverify accepts is left out. Every decision is written to the log with console.log, which you can read under Executions in the Apps Script editor.
Decide what happens when verification fails
Not every failure means the visitor is a bot, so the script sorts failures into two groups:
- Fail closed: reject, send nothing. The token is missing, too long, invalid, expired, already used or issued for a different hostname. Those are the signs of a bot posting straight to your URL, or of a page that isn’t yours.
- Fail open: send, with “[unverified]” in the subject. The secret isn’t set, Cloudflare says the secret is wrong, or Cloudflare can’t be reached or returns an error. None of those are the visitor’s fault. They’re problems with your setup or a brief outage.
This is a trade-off. Failing open means a setup mistake can’t silently throw away a real enquiry from a client. Instead, you get the message with a subject line that tells you something needs fixing. A bot also can’t use this to get through: it can’t make your secret go missing or make Cloudflare unreachable from Google’s servers. The risk is limited to spam getting through during a real outage or until you fix your configuration.
The stricter option is to fail closed every time and return rejected wherever the script above returns unverified. Choose that if you get a lot of spam and someone checks the Executions log regularly. Just be aware that any configuration mistake will then reject every real visitor, and they’ll be told they failed a bot check.
Grant the new permission and update the existing deployment
This step catches nearly everyone. Calling UrlFetchApp needs an extra Google permission (https://www.googleapis.com/auth/script.external_request). Deploying a new version doesn’t ask the owner for it: Google’s authorization guide says that after you add code that needs new permissions, you must run a function in the script editor once to trigger the authorization prompt. The script then fails with “You do not have permission to call UrlFetchApp.fetch” as soon as it reaches the Cloudflare check. With the fail-open policy above, those enquiries still reach you marked “[unverified]”. With fail-closed, every real visitor would be turned away.
To grant the permission:
- In the editor, choose
checkSetupfrom the function menu and click Run. - Approve the authorization prompt with the Google account that owns the script. For a script you wrote yourself, Google may warn that the app isn’t verified. Choose Advanced, then go to the project.
- Check the log. It should say
TURNSTILE_SECRET is setand show a reply from Cloudflare containing"success":false. That’s expected, because your real secret rejects the dummy token. If you seeinvalid-input-secret, paste the secret again.
Then publish the new code on the deployment you already have, so the /exec URL in your form doesn’t change:
- Click Deploy > Manage deployments.
- Select the active web app deployment and click Edit (the pencil icon).
- Under Version, choose New version and click Deploy.
Don’t use New deployment. It creates a new URL, and your live form would keep posting to the old code. Make sure the deployment still has Execute as: Me and Who has access: Anyone. Google’s deployment guide confirms that editing an existing deployment keeps the same URL.
Test it end to end
Check Cloudflare’s test keys from a terminal
Cloudflare publishes test keys that always pass or always fail, along with a dummy token. You can use them to see what Siteverify returns before touching your live form:
apt-get update
apt-get install -y curl jq# This secret always passes:
curl -s https://challenges.cloudflare.com/turnstile/v0/siteverify \
-d secret=1x0000000000000000000000000000000AA \
-d response=XXXX.DUMMY.TOKEN.XXXX | jq '.success'
# This secret always fails:
curl -s https://challenges.cloudflare.com/turnstile/v0/siteverify \
-d secret=2x0000000000000000000000000000000AA \
-d response=XXXX.DUMMY.TOKEN.XXXX | jq '.success'true
falseFor local development, you can put the test site key 1x00000000000000000000AA in the page and the test secret 1x0000000000000000000000000000000AA in Script Properties. A test secret always reports the hostname as example.com, so add 'example.com' to allowedHostnames while you test. Swap the real keys back in, and remove example.com, before you publish.
Send a real test enquiry
Publish the site, open the contact page in a private browser window and send a short test. You should see the thank-you message under the button without leaving the page. Then confirm the message actually arrived in the destination mailbox. If it didn’t, look in the inbox of the Google account that owns the script for a bounce notice, and check Executions for errors. If you can, send notifications to a Google Group or shared mailbox, so a staff change doesn’t break them.
Confirm a request without a token is rejected
Finally, act like a bot: post to the web app directly with no token. The -L flag follows Apps Script’s redirect to the reply (content service docs).
curl -sL "https://script.google.com/macros/s/<DEPLOYMENT_ID>/exec" \
-d name=Test -d email=[email protected] -d message=Hello -d format=json{"ok":false,"error":"verification"}Nothing should arrive in the mailbox, and the Executions log should show Rejected: no Turnstile token.
If your site sends a Content Security Policy header, allow https://challenges.cloudflare.com for scripts and frames, and allow your Apps Script URL in connect-src. GitHub Pages doesn’t set one by default.
Turnstile stops automated submissions. It won’t stop a person who’s paid to fill in forms by hand, so expect the occasional junk message. If you send form data to a spreadsheet as well as by email, our Google Form response emailer article covers the Apps Script email side in more detail.
Need more help?
Is your website form sending spam, or has it gone quiet when it shouldn’t have? Our IT Operations service looks after websites, email and the small automations that connect them for nonprofits, law firms and mission-driven organizations. Contact us and we’ll get right back to you.