My first function on Cloudflare Pages

During the weekend, I decided to change my contact form.
Objective: replacing the embed form via an iframe with a static form
What’s used:
Cloudflare
Pages
Pages Function
Turnstile
Telegram bot
BotFather is the tool to create a Telegram bot.
Captcha: Turnstile
For the captcha, I decided to use Turnstile from Cloudflare.
You don’t have to click on pictures or write an alphanumeric code.
It’s a fully automated validation, and manual verification is a simple checkbox.
Wow, that’s an improvement.
The form
Specific point: no action! Effectively, it’s a static form handled automatically by Cloudflare.
Tags
Multiple values can be selected
C2C
Contract
Digital Nomad friendly
Full Remote
Permanent
Other
First name
Last name
Company
Email address
Will be used to answer you.
Message
Submit
Basic form with two lines dedicated to the captcha:
- load the JS file
- the div where the captcha will be visible
The function
At the root for your repository, a little step:
My function file is contact.ts
, which applies on /contact
.
Big difference between a function and a worker
You can’t access environment variables/secrets, so you need to add them directly to your code. It’s the critical part that I learned doing this first function.
My big function
I want a function doing some simple steps:
- Verify the captcha (token)
- Get form values
- POST form values to an API endpoint (I don’t use emails!)
- Notify me on Telegram
- Thank you page
Static forms
I use the static-forms
provided by Cloudflare with a small change to have the possibility to run async code.
;
A quick override adding async
at the respondWith
.
Verify the captcha (token)
;
;
;
if outcome
It’s like the snippet in the documentation, but I needed to add the header, or it won’t work. When the captcha is ok, I go to the next step
Parsing form values
I prepare the body for the request.
;
I can have multiple tags, so I need to do the getAll.
Preparing Telegram notification body
;
Send form values to the API
await "https://MY_SUBDOMAIN/MY_ENDPOINT", ;
Send Telegram notification
await "https://api.telegram.org/botTELEGRAM_BOT_TOKEN/sendMessage", ;
Thank you page
Just creating a Response with the good Content-Type
;
"Content-Type", 'text/html;charset=UTF-8';
return res
Conclusion
Functions is the perfect extension of Pages without needing to use a full-featured worker.
In addition, I’m impatient to have Rust/WASM available for Functions because JS/TS isn’t for me.