Cloudflare Workers Tutorial Part-3: Writing Basic Code

In this part of the tutorial we will write basic code for Cloudflare Workers.

1. Hello World

Just a basic example from Cloudflare for printing hello world.

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

/**
 * Respond to the request
 * @param {Request} request
 */
async function handleRequest(request) {
  return new Response('hello world', {status: 200})
}
Output of hello world program

2. 301 Redirect

addEventListener('fetch', event => {
  event.respondWith(handleRequest())
})

async function handleRequest() {
  return Response.redirect('https://blog.devarshi.pro', 301)
}

To test this, I will be using cURL.

curl -XGET -IL http://techtorrent.org/

As you can see in above image, the request was redirected to getinto.in.

3. 301 Redirect on match

If URL has /redirect/me in the path we will redirect the request to the home page and print message.

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const regex = RegExp('redirect\/me')

  if ( request.url.match(regex) ) {
    path_regex_match = true
    return Response.redirect('https://techtorrent.org', 301)
  }
  return new Response('you have been redirected', {status: 200})
}

Now, if you visit site at techtorrent.org/redirect/me you will be redirected to the techtorrent.org

Don’t forget to replace techtorrent.org with your domain name.

4. Fetching request headers

In this example, we will pass a header in the request secret-header. If the secret-header is in the request with secret-value as the header value we will print a secret message.

In this, I have used cURL with -H flag to pass our secret-header

A secret value will be printed if you pass a secret header
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {

  const secret_header_value = request.headers.get('secret-header')
  if ( 'secret-value' ===  secret_header_value ) {
    return new Response('🔐 This is your super secret code : DCzFAezXgTV3At\n', {status: 200})
  }

  return new Response('Hey there 👋\n', {status: 200})
}

5. Get Emojis on /emojis

Let’s return some emojis on techtorrent.org/emojis

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {

  if ( request.url.match('/emojis') ) {

  let emojis="\
😀 😃 😄 😁 😆 😅 😂 🤣 😎 😉 \n\
🏀 🏈 ⚾ 🥎 🎾 🏐 🏉 🥏 🎱 🏏 \n\
🏎 🚲 🛩 🚀 ⛵ 🗺 🏖 🏝 🏜 🏞 \n"

  return new Response(emojis , {status: 200})
  }

  return new Response("Hey there!" , {status: 200})
  
}

You can always check Cloudflare Worker Documentation for in-depth knowledge.

This was it for part 3, writing basic code for Cloudflare Workers. In part 4 we will see how to Proxy and Cache requests on Cloudflare.

Leave a Reply

Your email address will not be published. Required fields are marked *