Skip to main content

Get Started with Cloudflare Workers

You can access to the Redis from the Cloudflare Workers using REST API of Upstash.

This tutorial explains the required steps to implement a Cloudflare Workers function that shows a page counter where the state is stored in Redis.

Step 1: Create database on Upstash#

If you do not have one, create a database following this guide. In the database page, click the button REST API and copy the REST URL.

Step 2: Cloudflare Workers Function#

Normally, it is best to create a Cloudflare Workers project using cli (wrangler) as described here. But you can try our example in the Workers Playground. Copy and paste the below code to the Workers Playground but you need to change the enpoint including the token:

addEventListener("fetch", event => {  event.respondWith(handleRequest(event.request))})
async function handleRequest(request) {let res = await fetch("https://us1-cool-python-31312.upstash.io/incr/counter\?_token\=AXpWASQgN2QxMWRlYzdfgmI4Yy0234RjLThjNTgtYWRmYTljODE4OGY2MjdmNWM1MmE1ZDE3NTMwMzYzYjAzYWI=")text = await res.text()return new Response("view count:" +JSON.parse(text).result)}

The above code simply increments a Redis counter with each Cloudflare Workers request and return the current value.

Next Steps#

  • You can keep the token in a secret or env variable as a more secure way.
  • You can use other Redis commands as described here
  • You can set up a more complex project using wrangler.