Trigger Cloudflare Workers from database changes
How to use Sequin to trigger Cloudflare Workers from database changes.
Cloudflare Workers are serverless functions that run on Cloudflare’s global network.
Often, you want to trigger a Cloudflare Worker when a database row changes. For example, you may want to trigger a worker as a side-effect of a database change, or fan out work to multiple services.
In this guide, you will learn how to setup Sequin to trigger a Cloudflare Worker when a database row changes.
Prerequisites
You are about to create a simple Cloudflare Worker that logs a message to the console. Sequin will trigger this worker by sending a HTTP POST request to the worker’s URL with the payload of the database row that changed.
You’ll need the following:
- A Cloudflare account
- A Sequin account
- A Postgres database (Sequin works with any Postgres database version 12+ - including Neon) with a basic
users
table containing anid
column and aname
column.
Create a Cloudflare Worker
Start by creating a new Cloudflare Worker that takes in a Sequin change event as a payload and logs the payload to the console.
Create a new Cloudflare Worker
- Log in to your Cloudflare dashboard and navigate to the “Workers and Pages” section.
- Click on “Create Worker”.
- Give your service a name (e.g., “user-worker”) and click “Deploy”.
Cloudflare will create a new worker.
Add worker code
Click the Edit code button.
Replace the default code in the worker editor with the following:
export default {
async fetch(request, env) {
// Verify the Sequin webhook secret
const authHeader = request.headers.get('authorization');
if (!authHeader || authHeader !== `Bearer ${env.SEQUIN_WEBHOOK_SECRET}`) {
return new Response('Unauthorized', { status: 401 });
}
try {
const payload = await request.json();
const { record } = payload;
if (record && record.name) {
console.log(`Hello ${record.name}`);
} else {
console.log('No name found in the payload.');
}
return new Response('Success', { status: 200 });
} catch (error) {
console.error('Error processing request:', error);
return new Response('Internal Server Error', { status: 500 });
}
},
};
This worker first checks the authorization header to make sure the request is coming from Sequin. Then it processes the payload (which contains the database row that changed) and logs the name from the payload to the console.
Click the Deploy button to deploy your worker.
Add the SEQUIN_WEBHOOK_SECRET environment variable
- In your worker’s settings, go to the “Settings” tab.
- Scroll down to the “Variables and Secrets” section.
- Click ”+ Add”.
- Set the variable name as
SEQUIN_WEBHOOK_SECRET
and the value to a secure secret of your choice. - Click “Deploy”.
You will need to use this secret value in the Sequin dashboard when you create the push consumer.
Get the worker's URL
Under the “Settings” tab, find the “Domains & Routes” section.
Copy the worker’s URL. You will need this URL in the Sequin dashboard when you create the push consumer.
You’ve successfully created a Cloudflare Worker that logs a message to the console when Sequin sends a HTTP POST request to the worker’s URL.
Create a Sequin Push Consumer
Create a new Sequin push consumer that detects changes to the users
table and sends a HTTP POST request to the Cloudflare Worker’s URL.
Connect Sequin to your database
- Login to your Sequin account and click the Add New Database button.
- Enter the connection details for your Postgres database.
- Follow the instructions to create a publication and a replication slot by running two SQL commands in your database:
create publication sequin_pub for all tables;
select pg_create_logical_replication_slot('sequin_slot', 'pgoutput');
- Name your database and click the Connect Database button.
Sequin will connect to your database and ensure that it’s configured properly.
Create a Push Consumer
Create a push consumer that will capture users from your database and deliver them to your Cloudflare Worker:
- Navigate to the Consumers tab and click the Create Consumer button.
- Select your
users
table (i.epublic.users
). - For this guide, you want to capture all changes to the
users
table. To do this, select Changes and click Continue. - Select to capture
inserts
,updates
, anddeletes
. No need to add a filter for now. Click Continue. - On the next screen, select Push to have Sequin send the events to your webhook URL. Click Continue.
- Now, give your consumer a name (i.e.
users_push_consumer
) and in the HTTP Endpoint section, click New HTTP Endpoint. - Enter your Cloudflare Worker’s URL. Then click to Add Encrypted Header and add an encryption header with the key
Authorization
and the valueBearer SEQUIN_WEBHOOK_SECRET
, using the secret value you set in your worker’s environment variables. Click Create Endpoint. - Back in the tab where you were creating your consumer, click the refresh button by the Endpoints section and select the endpoint you just created. Click Create Consumer.
Your Sequin consumer is now created and ready to send events to your Cloudflare Worker.
Test end-to-end
Create a new user in your database
insert into
users (name)
values
(
'John Doe'
);
Trace the change in the Sequin dashboard
In the Sequin console, open the Messages tab on your consumer and confirm that a message was delivered.
Confirm the event was received by your Cloudflare Worker
- Go to your Cloudflare dashboard and navigate to your worker.
- Click on the “Logs” tab.
- You should see a log entry:
Hello John Doe
:
You’ve successfully triggered a Cloudflare Worker from a database change!
Next steps
Modify this example to suit your needs:
- Create Cloudflare Workers to perform side-effects, fan out work, and more.
- If you need to run long-running jobs, consider using Cloudflare Durable Objects in tandem with Workers.
- Tune your consumer configuration to suit your volume of work.
- Implement additional security measures, such as Cloudflare Access for enhanced authentication and authorization.
Was this page helpful?