How to Deploy a Cloudflare Worker with Wrangler: A Complete Step-by-Step Guide

13 views 0 likes 0 comments 20 minutesOriginalTutorial

A hands-on guide to building and deploying Cloudflare Workers using the Wrangler CLI. This tutorial covers environment setup, project initialization, local debugging, wrangler.toml configuration, cloud deployment, and common troubleshooting tips for backend and full-stack developers diving into edge computing.

#Serverless #Cloudflare #Wrangler #Edge Computing #CLI Tool #Backend Development #TypeScript
How to Deploy a Cloudflare Worker with Wrangler: A Complete Step-by-Step Guide

A Practical Guide to Cloudflare Workers: From Installation to Deployment with Wrangler

Why You Should Care About Edge Computing

Over the past six months, my backend team has been experimenting with various deployment architectures. Traditional Spring Boot microservices deployed on Alibaba Cloud suffer from slow cold starts, and we constantly have to worry about server scaling, CDN configuration, and global node deployment. Last month, I got my hands on Cloudflare Workers. Using the Wrangler CLI, I deployed a lightweight API to over 275 global edge nodes in just a few minutes, achieving remarkably low latency.

If you're tired of tedious server operations and want to run a globally available API or middleware with minimal code, this guide will walk you through the entire process step-by-step: Install → Initialize → Local Debug → Configure → Deploy.

Prerequisites

Before we begin, make sure you have the following ready:

  • Node.js 18+: Wrangler runs on the Node.js ecosystem. Using nvm for version management is highly recommended.
  • npm or pnpm: Package manager. pnpm is recommended for its speed and disk space efficiency.
  • Cloudflare Account: Free to register. You'll need it for deployment authentication.
  • Basic JavaScript/TypeScript Knowledge: The Workers runtime is V8-based, so the syntax is almost identical to browser-side JS/TS.

If you're completely new to Serverless or Edge Computing, don't worry. This guide focuses on practical implementation rather than deep architectural theory.

Step 1: Install Wrangler

Open your terminal and install Wrangler globally:

bash 复制代码
npm install -g wrangler
## or using pnpm
pnpm add -g wrangler

After installation, verify it:

bash 复制代码
wrangler --version

Why do this? Wrangler is Cloudflare's official command-line tool. It handles project creation, local server startup, configuration validation, and cloud deployment. It essentially acts as a scaffold, build tool, and deployment client rolled into one. Once installed, all subsequent operations are handled through a single CLI.

Step 2: Log in to Cloudflare

After installation, you need to let Wrangler know which developer account it should use:

bash 复制代码
wrangler login

This command will automatically open your browser, prompting you to log in to Cloudflare and authorize Wrangler to access your account. Upon successful authorization, the terminal will display Successfully logged in.

Why do this? Workers need to be deployed to Cloudflare's cloud infrastructure. Wrangler requires valid credentials to create resources on your behalf. This step essentially issues a "passport" to the CLI tool, eliminating the need to re-enter passwords for future deployments.

Step 3: Initialize a Project

Navigate to a clean directory and initialize your first Worker project:

bash 复制代码
mkdir my-first-worker && cd my-first-worker
wrangler init

During initialization, Wrangler will ask a few questions:

  • Project type: Select Hello World template.
  • Use TypeScript: Highly recommended to select yes.
  • Create a Git repository: Choose based on your needs.

Once finished, your directory structure should look roughly like this:

复制代码
my-first-worker/
├── src/
│   └── index.ts        # Worker entry file
├── package.json
├── tsconfig.json
└── wrangler.toml       # Core configuration file

Open src/index.ts, and you'll see something like this:

typescript 复制代码
export interface Env {
  // Environment variable definitions
}

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    return new Response("Hello from Cloudflare Workers!");
  },
};

Why fetch? The Workers programming model closely resembles the browser's Fetch API. You receive a Request object, process it, and return a Response object. There's no Express, no routing libraries—just a pure request-response cycle. This minimalist design actually makes the code incredibly easy to understand and maintain.

Step 4: Local Development & Debugging

During development, you don't need to deploy to the cloud every time you change a line of code. Wrangler provides a local development server:

bash 复制代码
wrangler dev

After startup, you'll see output similar to this:

复制代码
⛅️ wrangler x.x.x
───────────────────
Your worker has access to https://localhost:8787

Open http://localhost:8787 in your browser, and you'll see Hello from Cloudflare Workers!.

You can now freely modify src/index.ts. Wrangler automatically watches for file changes and hot-reloads, providing a seamless experience. This works similarly to the watch mode in Vite or Nodemon, backed by a locally simulated Workers Runtime.

Step 5: Understanding wrangler.toml Configuration

This file is the "central nervous system" of your project. Opening wrangler.toml reveals:

toml 复制代码
name = "my-first-worker"
main = "src/index.ts"
compatibility_date = "2024-01-01"

## [vars]           # Environment variables
## MY_VAR = "something"

## [[kv_namespaces]] # KV Storage
## binding = "MY_KV"
## id = "xxxxxxxx"

Key fields explained:

  • name: The Worker's name, which becomes part of the subdomain after deployment (e.g., my-first-worker.<your-account>.workers.dev).
  • main: The entry file path, telling Wrangler where to start compiling.
  • compatibility_date: This is crucial! Cloudflare continuously updates the Workers Runtime. This date determines which API version your code uses. It's best practice to always set it to the current or a recent date to access the latest features while avoiding compatibility issues.
  • [vars]: Defines environment variables (e.g., API keys, DB connection strings). At runtime, Workers can access them via env.MY_VAR.
  • [[kv_namespaces]]: Used to bind Cloudflare KV storage (a Redis-like key-value database).

After writing the config, you can validate it before deploying using wrangler deploy --dry-run.

Step 6: Practical Example – Deploy a Routed JSON API

Outputting "Hello World" is fine, but let's build a functional API. Modify src/index.ts:

typescript 复制代码
export default {
  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url);
    const path = url.pathname;
    
    if (path === "/api/time") {
      return new Response(
        JSON.stringify({ now: new Date().toISOString(), server: "Cloudflare Worker" }),
        { headers: { "Content-Type": "application/json" } }
      );
    }
    
    if (path === "/api/echo" && request.method === "POST") {
      const body = await request.json();
      return new Response(
        JSON.stringify({ received: body }),
        { headers: { "Content-Type": "application/json" } }
      );
    }
    
    return new Response("Not Found", { status: 404 });
  },
};

Once local verification passes, execute the deployment:

bash 复制代码
wrangler deploy

The first deployment creates a Worker matching the name in wrangler.toml, automatically builds it, and uploads it to Cloudflare. Upon success, you'll get a public URL like:

复制代码
Published my-first-worker (x.xx s)
  https://my-first-worker.<your-account>.workers.dev

Use a browser or curl to visit https://<your-URL>/api/time, and you'll receive a UTC timestamp.

Why deploy this way? Deploying with Wrangler essentially compiles your TypeScript code into a Workers-compliant format, packages it, and uploads it to Cloudflare's edge network. You don't need to manage Docker, Nginx, or reverse proxies—Cloudflare handles it all.

Common Issues & Troubleshooting Tips

  1. wrangler dev fails with Port 8787 already in use
    The port is occupied. Specify another port using wrangler dev --port 9000, or kill the occupying process with lsof -i :8787.

  2. TypeScript compilation error: Cannot find Request / Response types
    The Workers Runtime provides these global types, but your IDE might not recognize them. Install @cloudflare/workers-types to fix it:

    bash 复制代码
    npm install -D @cloudflare/workers-types

    Then, add ["@cloudflare/workers-types"] to the types array in tsconfig.json.

  3. Deployment fails with Error: Missing account ID
    This usually happens if you have multiple Cloudflare accounts or your wrangler login session expired. Re-run wrangler login or manually specify account_id in wrangler.toml.

  4. Local wrangler dev behavior differs from production
    While the local server is highly compatible, it's still a simulation. Some advanced features (like Durable Objects or Queues) may not be fully supported locally. Regularly deploy with wrangler deploy for real-world testing.

Summary

Here's what we covered today:

  1. Installed Wrangler and completed account login.
  2. Initialized a project and understood the directory structure.
  3. Used wrangler dev for local development and debugging.
  4. Deciphered the core wrangler.toml configuration.
  5. Wrote a routed API and deployed it live.

In under 30 minutes, you now have a globally accessible backend API. No rented servers, no Nginx configuration, no Dockerfiles.

Next steps to explore:

  • Configure environment variables and Secrets in wrangler.toml.
  • Integrate Cloudflare KV or D1 databases to add state to your Workers.
  • Use wrangler pages to deploy full-stack applications.
  • Explore the Middleware pattern for request interception and authentication.

The Cloudflare Workers ecosystem is growing rapidly, and Wrangler, as the official CLI, has matured significantly. If you're exhausted by traditional deployment workflows, I highly recommend spending a weekend running through this pipeline. Trust me, you'll thank yourself later.

See you in the comments if you have any questions.

Last Updated:2026-06-15 10:05:38

Comments (0)

Post Comment

Loading...
0/500
Loading comments...