Pages Functions — KV, D1 & R2 Bindings
In this tutorial, you'll learn about Pages Functions. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
This tutorial explains how to bind Cloudflare KV (key-value store), D1 (Serverless SQL database), and R2 (S3-compatible object storage) to Pages Functions, giving your full-stack applications durable state at the edge. Serverless backends need persistent storage for user sessions, database records, and file uploads. The DodaTech feedback system uses D1 to store user submissions and KV to cache frequently accessed configuration data for faster response times.
Understanding Bindings
Bindings connect your Pages Functions to Cloudflare storage services without managing connection strings or API keys. You configure them in the Cloudflare dashboard under your Pages project settings. Each binding gets a name that you use to access the resource from your function code.
flowchart LR A[Pages Function] --> B[KV Binding] A --> C[D1 Binding] A --> D[R2 Binding] B --> E[Key-value data] C --> F[SQL queries] D --> G[Object storage] style B fill:#f90,color:#fff style C fill:#f90,color:#fff style D fill:#f90,color:#fff
KV Namespace Binding
KV provides low-latency key-value storage for configuration, session data, and cached responses. Values are replicated across Cloudflare data centers for global read performance.
// functions/api/config.js
export async function onRequest(context) {
const settings = await context.env.SETTINGS.get('app-config');
if (!settings) {
return new Response('Config not found', { status: 404 });
}
return new Response(settings, {
headers: { 'Content-Type': 'application/json' }
});
}
// Expected output: {"theme":"dark","maxUploads":10,"features":["analytics","comments"]}
// functions/api/counter.js
export async function onRequest(context) {
const key = 'page-views';
let views = parseInt(await context.env.COUNTER.get(key)) || 0;
views++;
await context.env.COUNTER.put(key, views.toString());
return new Response('Page views: ' + views);
}
// Expected output after 3 visits: Page views: 3
D1 Database Binding
D1 is a Serverless SQL database built on SQLite. It supports prepared statements, transactions, and parameterized queries for structured data.
// functions/api/users.js
export async function onRequest(context) {
const { results } = await context.env.DB.prepare(
'SELECT id, name, email FROM users WHERE active = ?'
).bind(1).all();
return new Response(JSON.stringify(results), {
headers: { 'Content-Type': 'application/json' }
});
}
// Expected output: [{"id":1,"name":"Alice","email":"alice"@example".com"},{"id":2,"name":"Bob","email":"bob"@example".com"}]
R2 Object Binding
R2 provides S3-compatible object storage for files, images, and backups with no egress fees.
// functions/api/upload.js
export async function onRequest(context) {
const formData = await context.request.formData();
const file = formData.get('file');
if (!file) {
return new Response('No file uploaded', { status: 400 });
}
await context.env.BUCKET.put(file.name, file.stream());
return new Response('Uploaded: ' + file.name);
}
// Expected output: Uploaded: screenshot.png
Security Considerations
Bindings expose storage resources to your functions. Always validate user input before writing to KV, D1, or R2. Use parameterized queries with D1 to prevent SQL Injection attacks. The Durga Antivirus Pro team applies strict input validation on all storage bindings to protect user data.
FAQ
Practice Questions
- What method do you call on a KV binding to retrieve a stored value?
- Which D1 API method executes a SQL query and returns all matching rows?
- What parameter does the R2 put method accept for streaming file data?
Summary
Cloudflare Pages Functions bind to KV, D1, and R2 for durable storage without managing servers. KV handles simple key-value data, D1 runs SQL queries, and R2 stores files and objects. You configure bindings in the dashboard and access them through context.env in your function handlers.
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro — security-first tools for the modern web.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro