Building Runtime-agnostic Apps/Packages with JavaScript
Node.js popularized the concept of running JavaScript on the server. Today, there are more JavaScript runtimes intended for building server-based applications, with Bun and LLRT among the most recent I'm aware of. Deno has been around for some years, and their Version 2 release seems to hit a chord because it has better compatibility with the Node.js API. Some of these runtimes have adopted Web Platform APIs to allow the same API to be used both in the browser and the server (e.g., web crypto API)—however, they also have runtime-specific APIs. For example, Deno has specific APIs like Deno.env which behaves like process.env in Node.js but with more methods to get, set or delete environment variables. Each platform has runtime-specific APIs that make certain tasks simpler to achieve. But how can you use a runtime-specific API and still allow your app/program to work across platforms (i.e., runtime-agnostic)? I will show you the best way to detect the runtime/platform and what you can do with it. I’ll start with the best option, then wrap up with common suggestions that will likely fail. The Secret Sauce

Node.js popularized the concept of running JavaScript on the server. Today, there are more JavaScript runtimes intended for building server-based applications, with Bun and LLRT among the most recent I'm aware of. Deno has been around for some years, and their Version 2 release seems to hit a chord because it has better compatibility with the Node.js API.
Some of these runtimes have adopted Web Platform APIs to allow the same API to be used both in the browser and the server (e.g., web crypto API)—however, they also have runtime-specific APIs. For example, Deno has specific APIs like Deno.env
which behaves like process.env
in Node.js but with more methods to get, set or delete environment variables. Each platform has runtime-specific APIs that make certain tasks simpler to achieve. But how can you use a runtime-specific API and still allow your app/program to work across platforms (i.e., runtime-agnostic)?
I will show you the best way to detect the runtime/platform and what you can do with it. I’ll start with the best option, then wrap up with common suggestions that will likely fail.