keepcalculator

06 Numbers and Powers

Deno to Cloudflare Workers: Fix Compatibility Errors

Card No. 06·39566 · Updated · Standard formula, shown below

Moving Deno code to Cloudflare Workers often hits compatibility errors because the two runtimes differ in APIs, module resolution, and global objects. This guide walks you through identifying and fixing the most common issues, so your code runs smoothly on Workers. You’ll need your Deno project, a Cloudflare account, and the Wrangler CLI installed.

What You’ll Need

  • A Deno project with source files you want to migrate
  • Node.js and npm (for Wrangler)
  • Wrangler CLI installed globally (npm install -g wrangler)
  • A Cloudflare account (free tier is fine)
  • Basic familiarity with your code’s dependencies and APIs

Step-by-Step

  1. Create a new Workers project
    Run wrangler init my-worker in a new directory. This sets up wrangler.toml and a basic src/index.js. Copy your Deno source files into the src folder.
  2. Replace Deno-specific globals
    Deno globals like Deno.env, Deno.readFile, and Deno.writeFile don’t exist in Workers. Use Workers’ env parameter in the fetch handler for environment variables, and the caches API or KV for storage. For file operations, you’ll need to use a different approach—Workers don’t have a filesystem.
  3. Adjust import paths
    Deno uses URLs for imports (e.g., import { serve } from "https://deno.land/std/http/server.ts"). Workers use npm packages or relative paths. Replace remote Deno imports with npm equivalents. For example, use express or itty-router instead of Deno’s std library. If you have local modules, ensure relative paths are correct.
  4. Handle TypeScript configuration
    Deno’s TypeScript config is automatic. Workers use tsconfig.json for type checking. Create one if needed and set "types": ["@cloudflare/workers-types"] in compilerOptions to get Workers type definitions. Remove any Deno-specific deno.json or import_map.json.
  5. Replace Deno’s Web APIs with Workers equivalents
    Both runtimes support fetch, WebSocket, and streams, but some APIs differ. For example, Deno’s Deno.serve is replaced by Workers’ fetch handler. Use crypto.subtle for hashing (both support it). Check for Deno.metrics or Deno.permissions—these don’t exist in Workers.
  6. Update event listeners
    Deno apps often use addEventListener("fetch", handler)—that’s actually the same as Workers! But ensure you export the fetch handler as the default export in Workers: export default { fetch(request, env, ctx) { ... } }. If your Deno code uses Deno.serve, convert it to the fetch handler.
  7. Handle asynchronous tasks correctly
    Workers have a ctx.waitUntil() method for background tasks. Deno’s setTimeout works but won’t keep the Worker alive. Use ctx.waitUntil(promise) for tasks like logging or cleanup.
  8. Test locally with Wrangler
    Run wrangler dev to test your Worker locally. This simulates the Workers runtime and catches most compatibility errors before deployment. Fix any errors that appear.
  9. Deploy and test in production
    Once local tests pass, run wrangler deploy. Test the deployed URL with a few requests to ensure everything works.

Common Mistakes

  • Using Node.js built-ins like fs or path—Workers don’t have them. Use Cloudflare’s KV or D1 for storage, and URL APIs for paths.
  • Forgetting to remove Deno permissions—code that checks Deno.permissions will crash. Remove all permission checks.
  • Assuming both runtimes have the same global objects—for example, Deno is not defined in Workers. Always check for runtime-specific globals.
  • Not handling environment variables correctly—Deno uses Deno.env.get(), but Workers get env via the env parameter in the fetch handler.
  • Using TypeScript features that require Deno’s compiler—like import assertions or deno.land type definitions. Stick to standard TypeScript.

Tips

  • Start small: migrate a simple endpoint first, then expand.
  • Use a compatibility layer library like @deno/workers if you need many Deno APIs—but prefer manual fixes.
  • Leverage Cloudflare’s workerd runtime locally with wrangler dev to catch issues early.
  • For file uploads, use Workers’ request.formData() instead of Deno’s FormData (they’re similar but check for differences).
  • Keep your code modular so you can swap runtime-specific parts easily.

Troubleshooting

If you still get errors after following the steps:

  • “Cannot find module”—check your import paths. Workers use npm packages with node_modules; run npm install for any npm imports.
  • “Deno is not defined”—search your code for Deno. and replace each occurrence with the Workers equivalent.
  • “Cannot read property of undefined”—this often happens with env variables. Ensure you’re passing env to your handler and that the variable names match your wrangler.toml.
  • Type errors during build—run npx tsc --noEmit to check types. Install @cloudflare/workers-types and set types in tsconfig.
  • Runtime errors after deploy—check the Cloudflare dashboard logs. Add console.log statements and use wrangler tail to see real-time logs.

Frequently Asked Questions

Can I use Deno’s std library in Workers?

No, Deno’s std library is not compatible with Workers. Replace it with npm packages or Cloudflare’s built-in APIs.

Do I need to change my code for WebSockets?

Workers support WebSocket clients and servers. The API is similar to Deno’s, but you need to handle the upgrade in the fetch handler.

How do I handle environment variables?

In Workers, environment variables are passed as the env parameter in the fetch handler. Define them in wrangler.toml under [vars].

Can I use Deno’s Deno.readFile to read files?

No, Workers have no filesystem. Use Cloudflare KV for persistent storage or read from the request body.

Is there a way to run Deno code as-is on Workers?

Not directly. You need to adapt the code to Workers’ runtime. Some tools like deno2node can help, but manual fixes are usually needed.

What about Deno’s Deno.serve?

Replace it with the Workers fetch handler. The fetch handler receives a Request and returns a Response.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →