Back

A Beginner's Guide to Cloudflare Workers

A Beginner's Guide to Cloudflare Workers

If you’re looking to build modern web applications without managing servers, Cloudflare Workers offers a compelling solution that goes far beyond simple serverless functions. Unlike traditional platforms, Workers now provides everything needed for full-stack applications: SQL databases through D1, connections to existing PostgreSQL or MySQL via Hyperdrive, static asset hosting, and extensive Node.js compatibility—all running at the edge, close to your users.

This Cloudflare Workers tutorial covers the essential concepts and tools you need to get started, from understanding edge-based execution to building complete applications with modern database connectivity and asset management.

Key Takeaways

  • Cloudflare Workers run JavaScript, TypeScript, and Python, and can also execute Rust when compiled to WebAssembly, all at edge locations within 50 ms of users worldwide
  • D1 provides serverless SQLite databases with automatic replication at the edge
  • Hyperdrive enables efficient connections to existing PostgreSQL and MySQL databases
  • Workers support full-stack applications with static asset hosting and Node.js compatibility

What Are Cloudflare Workers?

Edge-Based Execution Explained

Cloudflare Workers are JavaScript, TypeScript, Python, or Rust functions that run on Cloudflare’s global network of data centers. Instead of executing on a single server, your code runs at the edge location nearest to each user, typically within 50 milliseconds of anyone on Earth.

This edge-based model means your application responds faster because requests don’t travel to a central server. The platform automatically handles scaling—whether you have ten users or ten million, Workers adjusts without configuration.

Core Concepts: Bindings and Environment

Workers use bindings to connect your code to resources. These aren’t traditional environment variables but direct connections to services:

  • KV namespaces for key-value storage
  • D1 databases for SQL operations
  • R2 buckets for object storage
  • Service bindings to other Workers
  • Hyperdrive connections to external databases

Each binding appears as a property on the env object passed to your Worker:

export default {
  async fetch(request, env, ctx) {
    // Access D1 database
    const result = await env.DB.prepare('SELECT * FROM users').all()
    return Response.json(result)
  }
}

Modern Database Options with Cloudflare D1 Database

D1: Production-Ready SQL at the Edge

The Cloudflare D1 database brings SQLite to the edge with automatic replication and backups. Unlike traditional serverless databases, D1 runs in the same locations as your Workers, eliminating network latency for database queries.

Creating a D1 database is straightforward:

npx wrangler d1 create my-database
npx wrangler d1 execute my-database --file=./schema.sql

Your Worker accesses D1 through bindings, making queries feel local:

const user = await env.DB.prepare('SELECT * FROM users WHERE id = ?')
  .bind(userId)
  .first()

Hyperdrive Connectivity for Existing Databases

Hyperdrive connectivity solves a common challenge: connecting Workers to existing PostgreSQL or MySQL databases, including those in private networks. Hyperdrive maintains connection pools at Cloudflare’s edge, reducing connection overhead by up to 30x.

Setting up Hyperdrive requires minimal configuration:

npx wrangler hyperdrive create my-postgres \
  --connection-string="postgresql://user:pass@host:5432/db"

Your Worker then uses familiar database libraries with the Hyperdrive connection:

import { Client } from 'pg'

export default {
  async fetch(request, env) {
    const client = new Client(env.HYPERDRIVE.connectionString)
    await client.connect()
    const result = await client.query('SELECT * FROM products')
    return Response.json(result.rows)
  }
}

Building Full-Stack Applications

Workers Static Assets and Routing

Workers static assets eliminate the need for separate hosting. Your HTML, CSS, JavaScript, and images deploy alongside your API code. The platform automatically serves static files with proper caching headers and compression.

Static asset handling requires an assets entry in wrangler.toml pointing to your public directory.

Project structure for a full-stack Worker:

my-app/
├── src/
│   └── index.js        # Worker code
├── public/
│   ├── index.html      # Static assets
│   ├── style.css
│   └── app.js
└── wrangler.toml       # Configuration

Routing handles both static and dynamic requests:

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url)
    
    if (url.pathname.startsWith('/api/')) {
      // Handle API routes
      return handleAPI(request, env)
    }
    
    // Serve static assets
    return env.ASSETS.fetch(request)
  }
}

Node.js Compatibility Layer Benefits

The Node.js compatibility layer enables thousands of npm packages to work in Workers. Unlike early versions that only supported web-standard APIs, Workers now support Node.js built-ins like Buffer, crypto, stream, and path.

Enable Node.js compatibility in your wrangler.toml:

compatibility_flags = ["nodejs_compat"]

This compatibility means existing Node.js code often works with minimal changes, making migration from traditional servers straightforward.

Local Development Workflow

Setting Up Your Environment

Start with Wrangler, Cloudflare’s CLI tool:

npm create cloudflare@latest my-app
cd my-app
npm run dev

Wrangler provides hot-reload development with access to all bindings locally. Your D1 databases, KV namespaces, and even Hyperdrive connections work in development mode.

Testing and Deployment

The local development server mimics production behavior:

# Test with local D1 database
npx wrangler d1 execute DB --local --file=./seed.sql

# Deploy to production
npm run deploy

Additional Platform Features

While this tutorial focuses on core concepts, Workers offers additional capabilities worth exploring:

  • Queues for background job processing
  • R2 event notifications for object storage triggers
  • Gradual Deployments for safe rollouts
  • Workers Analytics and structured logging for observability

These features integrate seamlessly as your application grows.

Conclusion

Cloudflare Workers has evolved from simple edge functions to a complete platform for modern web applications. With D1 for serverless SQL, Hyperdrive for existing database connectivity, built-in static asset hosting, and comprehensive Node.js compatibility, you can build full-stack applications that run globally with minimal configuration.

Start with a simple Worker, add a D1 database for data persistence, and gradually incorporate features like Hyperdrive or R2 as needed. The platform handles the complexity of global distribution, letting you focus on building your application.

FAQs

Yes, Workers can handle most backend tasks including API endpoints, database operations, authentication, and file storage. With D1 for SQL, KV for caching, R2 for object storage, and Hyperdrive for existing databases, Workers provides a complete backend solution that scales automatically.

Workers charges per request and compute time with a generous free tier of 100,000 requests daily. Unlike traditional hosting with fixed monthly costs, you only pay for actual usage. This makes Workers cost-effective for both small projects and high-traffic applications.

Use Queues for background processing, Durable Objects for stateful operations, or break tasks into smaller chunks. For tasks exceeding limits, consider combining Workers with external services or using Cloudflare's scheduled Workers for batch processing.

Workers provides local development with wrangler dev for testing, console logging visible in real-time logs, and integration with Chrome DevTools. The main difference is understanding the request-based lifecycle and using structured logging for production debugging.

Gain Debugging Superpowers

Unleash the power of session replay to reproduce bugs, track slowdowns and uncover frustrations in your app. Get complete visibility into your frontend with OpenReplay — the most advanced open-source session replay tool for developers. Check our GitHub repo and join the thousands of developers in our community.

OpenReplay