Skip to content

Latest commit

 

History

History
 
 

worker-aws

Template: worker-aws

Deploy to Cloudflare Workers

This is a template for using Amazon Web Services such as DynamoDB and SQS from a Cloudflare Worker.

This project is not related to, affiliated with, sponsored or endorsed by Amazon Web Services.

Setup

To create a my-project directory using this template, run:

$ npm init cloudflare my-project worker-aws
# or
$ yarn create cloudflare my-project worker-aws
# or
$ pnpm create cloudflare my-project worker-aws

Note: Each command invokes create-cloudflare for project creation.

index.js is the content of the Workers script. In handleRequest, uncomment the example for the service you want to try out.

You'll need to use wrangler secrets to add appropriate values for AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, plus any of the service specific secrets, e.g.

$ wrangler secret put AWS_ACCESS_KEY_ID
$ wrangler secret put AWS_SECRET_ACCESS_KEY
$ wrangler secret put AWS_AURORA_SECRET_ARN
$ wrangler secret put AWS_SQS_QUEUE_URL

Configuration of less sensitive values such as AWS_REGION can be done in the [vars] block of your wrangler.toml file if you'd prefer.

After that you can use wrangler publish as normal. See the wrangler documentation for more information.

AWS Resources

This template pieces together a few AWS products:

The Aurora RDS example assumes the following SQL structure:

CREATE DATABASE demo;

CREATE TABLE demo.friends (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=INNODB;

With this, you may insert new demo.friends values by submitting a POST request with JSON data:

$ curl -X POST https://<worker> -d '{"name":"alice"}'
$ curl -X POST https://<worker> -d '{"name":"bob"}'
$ curl -X POST https://<worker> -d '{"name":"carl"}'

And then you may retrieve a single demo.friends row by sending a GET request with an ID parameter:

$ curl https://<worker>?ID=1
#=> [[{"longValue":1},{"stringValue":"alice"},{"stringValue":"YYYY-MM-DD HH:mm:ss"}]]

$ curl https://<worker>?ID=2
#=> [[{"longValue":2},{"stringValue":"bob"},{"stringValue":"YYYY-MM-DD HH:mm:ss"}]]

AWS SDK for JavaScript

These examples use v3 of the AWS SDK for JavaScript, see that repository for more information.