Write Once, Run on Any Runtime: Practical Runtime-Agnostic TypeScript for Node, Deno, Bun and Cloudflare Workers
Tin Cloudflare mua lại Deno đang leo top Hacker News, và phần bình luận chia làm hai phe: một phe mừng vì Deno có "nhà giàu" chống lưng, phe kia lo bị vendor lock-in. Mình thấy câu hỏi thực tế hơn cho dev là: nếu ngày mai runtime bạn đang dùng đổi chủ, đổi giá hoặc đổi hướng đi, code của bạn mất bao lâu để chuyển sang chỗ khác? Với nhiều team mình từng làm cùng, câu trả lời là "vài tuần", vì…
Runtime-Agnostic TypeScript for Node, Deno, Bun and Cloudflare Workers: A Practical Approach
In recent years, each runtime has adopted a common set of APIs. This trend started a few years ago and now continues with support for Web Standard APIs: Request, Response, Headers, fetch, URL, URLSearchParams, ReadableStream, TextEncoder / TextDecoder, crypto.subtle, crypto.randomUUID(), structuredClone, and AbortController.
The primary rule for writing runtime-agnostic TypeScript code is to use only Web Standard APIs in the core logic. Any code that requires Node-specific modules such as fs, Deno.env, or env.MY_KV should be extracted into a thin adapter layer.
To create a core application, define an interface for dependencies, including a store for key-value storage. Implement a function to generate SHA-256 hashes for generating short URLs. Create a fetch handler that checks the URL path and performs appropriate actions, such as returning a health check response, shortening a link, or redirecting to a target URL.
The core application should not be aware of the runtime it is running on. Each entry file for a specific runtime should only read the configuration from that runtime and pass it to the core. Avoid using process.env within the core. Instead, inject the configuration as a dependency. Use an interface for storage, which allows for easy swapping of storage implementations.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.