Using Cloudflare as a serverless alternative to Redis

Using Cloudflare as a serverless alternative to Redis


0






Rahul Kumar (@rahul)

Using Cloudflare as a serverless alternative to Redis offers a compelling solution for developers seeking scalable and cost-effective data storage and caching solutions. While Redis is a popular choice for in-memory data storage and caching, it requires infrastructure management and maintenance. There are few other serverless alternatives as well, but in this post we'll only talk about Cloudflare KV

Agenda

We'll set Cloudflare Workers KV and integrate it into JavaScript. We'll implement REST endpoints for creating, reading and deleting key/value pairs. 

What Cloudflare?

Cloudflare, Inc. is an American company that provides content delivery network services, cloud cybersecurity, DDoS mitigation, Domain Name Service, and ICANN-accredited domain registration services. Cloudflare's headquarters are in San Francisco, California.

What is Cloudflare Workers KV?

Workers KV is a data storage that allows you to store and retrieve data globally. With Workers KV, you can build dynamic and performant APIs and websites that support high read volumes with low latency.

Steps to integrate Cloudflare KV

  • Create account if you don’t have
  • Create a KV name space
  • Get required tokens and parameters from Cloudflair dashboard
  • Make HTTP request to create/read/delete key/value

Cloudflare KV setup

The very first thing you need to do is create an account on Cloudflare if you don’t have one. You this article to learn more about creating an account. 

Create KV namespace

KV namespace is a key/value database replicated to Cloudflare’s global network.

  • Log in to dashboard
  • Select Workers & Pages > KV
  • Select Create a namespace.
  • Select Add

Once KV namespace is created, obtain the following from Cloufflare dashboard

  • Account ID
  • KV namespace id (You can get this from workers KV pages shown in the previous step)
  • Token with permission for workers KV read/write (See below)

To get a Cloudflare token, go to dash.cloudflare.com/profile > API tokens > Create token

Implementing REST APIs for KV

tokens

      const CLOUDFLAIR_ACCOUNT_ID = 'your account id';
const CLOUDFLAIR_KV_NAME_SPACE_ID = 'your kv namespace id'
const CLOUDFLAIR_TOKEN = 'your cloudflare token';
    

I am using NodeJs to implement KV REST APIs. 

Install the following npm packages to get help

Install Packages

      npm i form-data
npm i axios
    

Writing key/value pair

Cloud flare accepts multipart/form-data when writing key/value pair. So we'll be using the form-data package to create a multipart/form-data HTTP request body. 

Write key/value pair

      async function setKey(key, value) {
  const formData = new FormData();
  
  // you can write meta data along with key, but we are leaving it empty for now
  formData.append("metadata", "{}");

  // assuming value argument is a valid JSON, but it can be any arbitrary string
  formData.append("value", JSON.stringify(value));

  const options = {
    method: "PUT",
    url: `https://api.cloudflare.com/client/v4/accounts/${CLOUDFLAIR_ACCOUNT_ID}/storage/kv/namespaces/${CLOUDFLAIR_KV_NAME_SPACE_ID}/values/${key}`,
    headers: {
      "Content-Type": "multipart/form-data;",
      Authorization: `Bearer ${CLOUDFLAIR_TOKEN}`,
    },
    data: formData,
  };

  return axios.request(options);
}
    

Reading Key

Reading Key

      async function getKey(key) {
  const options = {
    method: "GET",
    url: `https://api.cloudflare.com/client/v4/accounts/${CLOUDFLAIR_ACCOUNT_ID}/storage/kv/namespaces/${CLOUDFLAIR_KV_NAME_SPACE_ID}/values/${key}`,
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${CLOUDFLAIR_TOKEN}`,
    },
  };

  try {
    const response = await axios.request(options);
    return response.data;
  } catch (error: any) {
    // if there is no key in the database then Cloudflare returns HTTP 404 status code
    if (error.response.status === 404) {
      return null;
    }

    throw error;
  }
}
    

Deleting Key

Deleting Key

      async function deleteKey(key) {
  const options = {
    method: "DELETE",
    url: `https://api.cloudflare.com/client/v4/accounts/${CLOUDFLAIR_ACCOUNT_ID}/storage/kv/namespaces/${CLOUDFLAIR_KV_NAME_SPACE_ID}/values/${key}`,
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${CLOUDFLAIR_TOKEN}`,
    },
  };

  return axios.request(options)
}
    

Add a thoughtful comment...

✨ Explore more tech insights and coding wonders with @dsabyte! Your journey in innovation has just begun. Keep learning, keep sharing, and let's continue to code a brighter future together. Happy exploring! 🚀❤️

  • #cloudflare
  • #http
  • #key
  • #value
  • #javascript

Subscribe to our newsletter.

Join the "News Later" community by entering your email. It's quick, it's easy, and it's your key to unlocking future tech revelations.

Weekly Updates

Every week, we curate and deliver a collection of articles, blogs and chapters directly to your inbox. Stay informed, stay inspired, and stay ahead in the fast-paced world of technology.

No spam

Rest assured, we won't clutter your inbox with unnecessary emails. No spam, only meaningful insights, and valuable content designed to elevate your tech experience.

© 2024 @dsabyte. All rights reserved