Pages Functions — Serverless Backend
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 introduces Cloudflare Pages Functions, a Serverless runtime that runs backend code alongside your static site at the edge. Functions handle dynamic requests like form submissions, user authentication, and API proxying without a dedicated server. DodaZIP uses a Pages Function to validate ZIP file metadata before upload, saving bandwidth and improving user experience.
What Are Pages Functions
Pages Functions are JavaScript or TypeScript files placed in a functions directory at the root of your project. Each file maps to a route automatically. Functions run on Cloudflare's Workers runtime, giving you access to the full Workers API including environment variables, KV storage, and D1 databases.
flowchart LR
A[Visitor request] --> B[Pages static assets]
B --> C{Matching function?}
C -->|No| D[Serve static file]
C -->|Yes| E[Run serverless function]
E --> F[Return dynamic response]
style E fill:#f90,color:#fff
style C fill:#f90,color:#fff
Creating Your First Function
A function is an exported onRequest handler that receives a request context and returns a response.
// functions/hello.js
export function onRequest(context) {
const { request } = context;
const url = new URL(request.url);
const name = url.searchParams.get('name') || 'World';
return new Response('Hello ' + name + '!', {
headers: { 'Content-Type': 'text/plain' }
});
}
// When visiting /hello?name=DodaTech
// Expected output: Hello DodaTech!
Handling Form Submissions
Functions can parse POST data and forward it to external services or databases.
// functions/submit.js
export async function onRequest(context) {
if (context.request.method !== 'POST') {
return new Response('Method not allowed', { status: 405 });
}
const formData = await context.request.formData();
const email = formData.get('email');
if (!email) {
return new Response('Email is required', { status: 400 });
}
return new Response('Submission received for ' + email, {
status: 200
});
}
// Expected output for POST with email=test@example.com:
// Submission received for test@example.com
// functions/api/data.js
export async function onRequest(context) {
const data = {
timestamp: Date.now(),
message: 'Data from the edge',
region: context.request.cf && context.request.cf.colo
};
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' }
});
}
// Expected output:
// { "timestamp": 1719123456789, "message": "Data from the edge", "region": "LHR" }
Environment Variables in Functions
You access environment variables through context.env. Set them in the Cloudflare Pages dashboard per environment.
// functions/api/config.js
export function onRequest(context) {
const apiKey = context.env.API_KEY;
if (!apiKey) {
return new Response('API key not configured', { status: 500 });
}
return new Response('API key is set', { status: 200 });
}
FAQ
Practice Questions
- What is the file naming convention for Pages Functions?
- What object does a Pages Function handler receive as its argument?
- How do you access environment variables inside a Pages Function?
Summary
Cloudflare Pages Functions turn a static site into a full-stack application. Place JavaScript files in the functions directory, and they handle dynamic requests at the edge. Functions support form handling, API endpoints, and external service integration.
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