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
We'll set Cloudflare Workers KV and integrate it into JavaScript. We'll implement REST endpoints for creating, reading and deleting key/value pairs.
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.
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.
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.
KV namespace is a key/value database replicated to Cloudflare’s global network.
Once KV namespace is created, obtain the following from Cloufflare dashboard
To get a Cloudflare token, go to dash.cloudflare.com/profile > API tokens > Create token
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
npm i form-data
npm i axios
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.
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);
}
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;
}
}
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! 🚀❤️
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.