Skip to content
jshacks.dev
Node.js

How to Share Code Between Node.js and the Browser

Write ES modules that run unchanged in Node.js 26 and the browser, split platform code behind package exports conditions and avoid traps that break one side.

7 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Node.js, Google Chrome, Swagger, Postman and GraphQL logos.

Validation rules written twice drift apart. The server rejects a username the form accepted, or the form accepts one the server rejects, and a user sees an error they cannot fix. Sharing one module between Node.js and the browser removes that class of bug, and since both now run ES modules natively, it is easier than it used to be. It is also easy to get subtly wrong: a shared file that imports node:fs breaks the bundle, one that touches window throws on the server, and a package that publishes only CommonJS fails in a browser with no build step. This post sets up a shared module on Node.js 26, shows the rules that keep it portable, and uses package exports conditions to ship different implementations where the platforms really differ.

Start with pure functions

The easiest code to share has no platform dependencies. A function that takes data and returns data runs anywhere.

shared/validate.jsJavaScript
const USERNAME = /^[a-z][a-z0-9_]{2,19}$/;

export function validateUsername(value) {
  if (typeof value !== "string") return "Username must be text";
  if (!USERNAME.test(value)) {
    return "Use 3 to 20 lowercase letters, digits or underscores, starting with a letter";
  }
  return null;
}

export function slugify(text) {
  return text
    .toLowerCase()
    .normalize("NFKD")
    .replace(/[̀-ͯ]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-|-$/g, "");
}

The module uses only language features: regular expressions, string methods, normalize. Those behave the same in V8 on both sides. In Node.js, import it like any other module.

server/check.jsJavaScript
import { validateUsername, slugify } from "../shared/validate.js";

console.log(validateUsername("ada_l"));
console.log(validateUsername("9lives"));
console.log(slugify("Crème Brûlée Recipes"));
Text
null
Use 3 to 20 lowercase letters, digits or underscores, starting with a letter
creme-brulee-recipes

And in the browser, the same file loads as a native module with no bundler.

index.htmlHTML
<script type="module">
  import { validateUsername } from "/shared/validate.js";

  const input = document.querySelector("#username");
  const message = document.querySelector("#message");
  input.addEventListener("input", () => {
    message.textContent = validateUsername(input.value) ?? "";
  });
</script>

Two requirements are easy to forget. The browser needs the full file extension in every import, ./validate.js and not ./validate, and Node.js ES modules need it too, so a shared codebase should always write it. And the server must send .js files with a JavaScript MIME type, or the browser refuses to execute the module with a message about a disallowed MIME type.

Keep platform APIs out of the shared core

A shared module is safe when its imports are either other shared modules or APIs that exist on both sides. Many APIs now do, and they are worth knowing.

APINode.js 26Browser
fetch, Request, Response, HeadersGlobalGlobal
URL, URLSearchParamsGlobalGlobal
TextEncoder, TextDecoderGlobalGlobal
crypto.subtle, crypto.randomUUID()Global cryptoGlobal crypto
AbortController, AbortSignal.timeout()GlobalGlobal
structuredCloneGlobalGlobal
ReadableStream, TransformStreamGlobalGlobal
BufferGlobalAbsent
process, __dirnamePresentAbsent
window, document, localStorageAbsentPresent

The practical rule: in shared code use the left-to-right intersection of that table and never reach for Buffer, process or window. For hashing, that means the web API.

shared/hash.jsJavaScript
export async function sha256Hex(text) {
  const bytes = new TextEncoder().encode(text);
  const digest = await crypto.subtle.digest("SHA-256", bytes);
  return [...new Uint8Array(digest)]
    .map((byte) => byte.toString(16).padStart(2, "0"))
    .join("");
}
server/hash-demo.jsJavaScript
import { sha256Hex } from "../shared/hash.js";

console.log(await sha256Hex("hello"));
Text
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

The same function returns the same digest in a browser console, as long as the page is a secure context, since crypto.subtle is only exposed over HTTPS and on localhost. That is a real difference worth a test: a page served over plain HTTP from another host has no crypto.subtle.

Detect the platform only at the edges

Sometimes a module has to know where it runs, for instance to read configuration. Do not scatter checks through the code. Push the difference into a small adapter and keep the logic above it clean.

shared/config.jsJavaScript
export function readSetting(name, source) {
  const value = source[name];
  if (value === undefined) throw new Error(`Missing setting: ${name}`);
  return value;
}

The caller supplies the source: process.env on the server, a window.__CONFIG__ object injected into the page in the browser. The function is testable with a plain object and has no idea where it runs. This inversion, passing in what differs, is almost always better than typeof window !== "undefined" branches inside business logic.

When you cannot avoid a check, use feature detection on the exact thing you need, not the platform name.

shared/storage.jsJavaScript
export function createStore() {
  try {
    if (typeof localStorage !== "undefined") {
      localStorage.setItem("__probe", "1");
      localStorage.removeItem("__probe");
      return {
        get: (key) => localStorage.getItem(key),
        set: (key, value) => localStorage.setItem(key, value),
      };
    }
  } catch {
    // Storage can exist and still throw, for example in a private window.
  }
  const memory = new Map();
  return { get: (key) => memory.get(key) ?? null, set: (key, value) => memory.set(key, value) };
}

The try and catch is not decoration. Browsers can expose localStorage and still throw on write when storage is blocked, so existence is not enough. Node.js 26 may also define a localStorage global when started with the right flag, which is another reason to probe the behavior you need instead of trusting a name.

Ship different code per platform with exports conditions

When two implementations are genuinely needed, such as a logger that uses console in the browser and a stream in Node.js, publish both under one import name. The exports field in package.json supports conditions, and both Node.js and bundlers read them.

package.jsonJSON
{
  "name": "@acme/shared",
  "version": "1.0.0",
  "type": "module",
  "exports": {
    "./validate": "./src/validate.js",
    "./logger": {
      "browser": "./src/logger.browser.js",
      "node": "./src/logger.node.js",
      "default": "./src/logger.browser.js"
    }
  }
}
src/logger.node.jsJavaScript
export function log(level, message) {
  process.stdout.write(`${JSON.stringify({ level, message })}\n`);
}
src/logger.browser.jsJavaScript
export function log(level, message) {
  console[level === "error" ? "error" : "log"](message);
}

Application code writes one import and each platform resolves its own file.

app.jsJavaScript
import { log } from "@acme/shared/logger";

log("info", "started");
Text
{"level":"info","message":"started"}

That output is what Node.js prints, because it matches the node condition. A bundler targeting the browser matches browser and prints started through console.log. Put the most specific condition first, since matching goes in object order, and always include default. The Node.js package exports documentation defines the condition names.

Because exports also hides everything not listed, consumers cannot deep-import @acme/shared/src/secret.js. That is a feature: the public surface is exactly what you list.

Test once, run on both

A shared module deserves its tests in the environment that is easiest to run, and Node.js is it. node:test needs no tooling.

shared/validate.test.jsJavaScript
import { test } from "node:test";
import assert from "node:assert/strict";
import { validateUsername, slugify } from "./validate.js";

test("accepts a valid username", () => {
  assert.equal(validateUsername("ada_l"), null);
});

test("rejects a leading digit", () => {
  assert.match(validateUsername("9lives"), /starting with a letter/);
});

test("slugify strips accents", () => {
  assert.equal(slugify("Crème Brûlée"), "creme-brulee");
});
Shell
node --test shared/
Text
✔ accepts a valid username (0.9ms)
✔ rejects a leading digit (0.2ms)
✔ slugify strips accents (0.3ms)
ℹ tests 3
ℹ pass 3
ℹ fail 0

For code that touches fetch or crypto.subtle, add one browser run in CI to catch the differences in the table above, because a green Node.js run does not prove the browser path.

Sharing types and constants without sharing behavior

Not everything shared needs to run. Constants, enumerations and message formats are the cheapest things to share and the most valuable, because a typo in a status string on one side is the kind of bug no unit test finds. Put them in a module with no imports at all.

shared/constants.jsJavaScript
export const ORDER_STATUS = Object.freeze({
  PENDING: "pending",
  PAID: "paid",
  SHIPPED: "shipped",
});

export const MAX_UPLOAD_BYTES = 5 * 1024 * 1024;

The server uses ORDER_STATUS.PAID when it writes a row, and the front end uses the same constant when it chooses a badge color. Renaming a status then becomes a single edit that both sides pick up, and a search for the constant finds every use. If you use TypeScript, the same file can export types, and import type statements vanish at build time, so they never reach the runtime.

Keep an eye on how this module is packaged. A monorepo with a workspace package is the common approach, where shared is a folder with its own package.json that both the server and client list as a dependency. The alternative of copying files drifts within a month. Whichever you choose, run the same tests against the shared package from one place, so both consumers see the same behavior.

Traps that break one side

  • A transitive CommonJS dependency. A browser cannot load require(). Check that every package you share publishes ES modules, or bundle.

  • **Buffer sneaking in.** A helper that calls Buffer.from(text).toString("base64") fails in the browser. Use btoa for ASCII or a TextEncoder approach for Unicode.

  • **Line endings and \r\n.** Text from a Windows form and from a Linux file differ, so normalize before comparing.

  • **Date and time zones.** Shared date code that formats with local time gives different results on a server in UTC and a laptop elsewhere. Format with an explicit timeZone.

  • **Different Intl data.** Both sides use ICU, but versions differ, so exact output of a locale format can vary slightly.

Also inBrowser
Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.