Sharing Code with the Browser

Discover the tools and techniques we can use to share code between the server and the browser.

One of the main selling points of Node.js is the fact that it’s based on JavaScript and runs on V8, a JavaScript engine that actually powers some of the most popular browsers: Google Chrome and Microsoft Edge. We might think that sharing the same JavaScript engine is enough to make sharing code between Node.js and the browser an easy task; however, this isn’t always true, unless we want to share only simple, self-contained, and generic fragments of code.

Developing code for both the client and the server requires a nonnegligible level of effort in making sure that the same code can run properly in two environments that are intrinsically different. For example, in Node.js, we don’t have the DOM or long-living views, while on the browser, we surely don’t have the filesystem and many other interfaces to interact with the underlying operating system.

Another contention point is the level of support for modern JavaScript features. When we target Node.js, we can safely adopt modern language features because we know which Node.js version runs on our servers. For instance, for our server code, we can safely decide to adopt async/await if we know that it’ll run on Node.js version 8 (or on a more recent version). Unfortunately, we can’t have the same confidence when writing JavaScript code for the browser.

This is because different users will have different browsers with different levels of compatibility with the latest language features. Some users might be using a modern browser with full support for async/await, while other users might still be using an old device with an old browser that does not support async/await.

Get hands-on with 1200+ tech skills courses.