Skip to main content

Dev tools and workflow · Intermediate · 20 min

Set up a JavaScript monorepo with pnpm workspaces

By Padding · Updated 18 Nov 2026
node:26 (Debian) · Node.js 26.13 LTS · pnpm 12.23.0 · TypeScript 7.0.2

You will have one repository holding a web app, an API and a shared TypeScript package, linked with pnpm 12 workspaces, sharing one lockfile and one catalog of versions, built in dependency order and with the API shipped on its own through pnpm deploy.

On this page

A monorepo is one Git repository that holds several packages: a web front end, an API and the code they share, for example. The benefit is that a change to the shared code and the apps that use it land in one commit, one review and one install. The cost is tooling: something has to link the packages to each other, install their dependencies once and run their scripts in the right order.

pnpm does that with workspaces. You list the package folders in a pnpm-workspace.yaml file, and pnpm installs every package in one go, links workspace packages to each other with symlinks, writes a single pnpm-lock.yaml at the root and lets you run scripts in one package, a chosen group or all of them.

In this tutorial you build a small shop repository with three packages:

  • @demo/shared, a TypeScript package with a price formatter and some sample products
  • @demo/api, a Node.js HTTP API that returns the products as JSON
  • @demo/web, a build script that writes a static HTML product page

Along the way you see the workspace: protocol, dependency-ordered builds, catalogs for keeping versions in one place, how pnpm's strict node_modules catches a dependency you forgot to declare, and pnpm deploy, which copies one package and only its dependencies into a folder you can ship.

The prices are in Nigerian naira and use the en-NG locale, because that is a realistic case for a shop built for West African customers. Swap in any currency code and locale you like. pnpm also helps on metered data: it keeps one copy of each package version in a store on your machine and links it into every project, so a second project that needs the same versions downloads nothing.

Step 1 · Install pnpm 12

Node.js used to ship a tool called Corepack that could switch on pnpm for you. Node.js stopped bundling it in version 25, so on Node.js 26 you install pnpm yourself. The simplest way is from npm, as a global package:

Bash
npm install -g pnpm@12.23.0
pnpm --version

If you followed the Node.js install tutorial, npm's global folder is ~/.npm-global, so this needs no sudo. pnpm 12 is a native program: the npm package downloads the right build for your operating system and processor while it installs.

pnpm also has a standalone installer that works without Node.js. It downloads a script and runs it, so read the script at that address first if you prefer to:

Bash
curl -fsSL https://get.pnpm.io/install.sh | sh -

Use one method, not both, or you will have two copies of pnpm on your PATH.

Check it worked

pnpm --version prints 12.23.0. If your shell says pnpm: command not found, open a new terminal so it picks up the updated PATH.

Step 2 · Create the workspace root

Make the repository folder with one folder for apps and one for shared packages:

Bash
mkdir -p ~/pnpm-monorepo-demo/apps/api ~/pnpm-monorepo-demo/apps/web ~/pnpm-monorepo-demo/packages/shared/src
cd ~/pnpm-monorepo-demo

The root gets its own package.json. It is marked private so it can never be published by mistake, and packageManager records the pnpm version the team uses, so everyone can see which one the lockfile was written with. The build script will build every package:

Bash
cat > package.json <<'JSON'
{
  "name": "pnpm-monorepo-demo",
  "private": true,
  "packageManager": "pnpm@12.23.0",
  "scripts": {
    "build": "pnpm -r build"
  }
}
JSON

Now the file that turns the folder into a workspace. packages lists globs for the folders that hold packages. catalog is a list of dependency versions that any package in the workspace can refer to by name. You will use it in a moment:

Bash
cat > pnpm-workspace.yaml <<'YAML'
packages:
  - apps/*
  - packages/*

catalog:
  typescript: 7.0.2
  escape-html: ^1.0.3
YAML

In pnpm 12, pnpm-workspace.yaml is also where pnpm settings go. An .npmrc file is read only for registry, authentication, TLS and proxy settings.

Check it worked

ls in ~/pnpm-monorepo-demo shows apps, package.json, packages and pnpm-workspace.yaml.

Step 3 · Write the shared TypeScript package

The shared package is written in TypeScript and compiled to JavaScript with type declarations, so the apps can import plain JavaScript and editors still see the types. Its exports map points at the compiled files in dist, and "typescript": "catalog:" means "use the TypeScript version from the catalog":

Bash
cat > packages/shared/package.json <<'JSON'
{
  "name": "@demo/shared",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "default": "./dist/index.js"
    }
  },
  "files": ["dist"],
  "scripts": {
    "build": "tsc"
  },
  "devDependencies": {
    "typescript": "catalog:"
  }
}
JSON
cat > packages/shared/tsconfig.json <<'JSON'
{
  "compilerOptions": {
    "target": "es2023",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "rootDir": "src",
    "outDir": "dist",
    "declaration": true,
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["src"]
}
JSON

The code stores prices in kobo, the minor unit, as whole numbers. Money kept as whole minor units never suffers from floating-point rounding. Intl.NumberFormat turns it into a display string for a locale:

Bash
cat > packages/shared/src/index.ts <<'TS'
export type Product = {
  id: string;
  name: string;
  priceMinor: number;
  currency: string;
};

export const sampleProducts: Product[] = [
  { id: "p1", name: "Solar lamp", priceMinor: 1850000, currency: "NGN" },
  { id: "p2", name: "Data bundle, 5 GB", priceMinor: 350000, currency: "NGN" },
  { id: "p3", name: "Phone case <slim>", priceMinor: 420000, currency: "NGN" },
];

export function formatPrice(priceMinor: number, currency: string, locale = "en-NG"): string {
  return new Intl.NumberFormat(locale, { style: "currency", currency }).format(priceMinor / 100);
}
TS

The angle brackets in the third product name are on purpose. They will show why the web page escapes text.

Install from the root, then build only this package with --filter:

Bash
pnpm install
pnpm --filter @demo/shared build

pnpm install reads pnpm-workspace.yaml, finds every package under apps/ and packages/ and installs them all. --filter @demo/shared runs the build script in that package only.

Check it worked

The install prints something like Scope: all 2 workspace projects (the root counts as one) and ends with Done. ls packages/shared/dist shows index.d.ts and index.js. There is one pnpm-lock.yaml, at the root, and none inside packages/shared. That single lockfile records the exact versions for every package in the repository.

Step 4 · Link the API to the shared package

The API depends on @demo/shared with the workspace: protocol. workspace:* tells pnpm to link the package from this repository, never to fetch a package of that name from the npm registry. If the package is missing from the workspace, the install fails instead of quietly downloading something else:

Bash
cat > apps/api/package.json <<'JSON'
{
  "name": "@demo/api",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "@demo/shared": "workspace:*"
  }
}
JSON
cat > apps/api/server.js <<'JS'
import { createServer } from "node:http";
import { formatPrice, sampleProducts } from "@demo/shared";

const port = Number(process.env.PORT ?? 3001);

const server = createServer((req, res) => {
  if (req.url === "/api/products") {
    const body = sampleProducts.map((p) => ({
      id: p.id,
      name: p.name,
      price: formatPrice(p.priceMinor, p.currency),
    }));
    res.writeHead(200, { "content-type": "application/json" });
    res.end(JSON.stringify(body));
    return;
  }
  res.writeHead(404, { "content-type": "application/json" });
  res.end(JSON.stringify({ error: "not found" }));
});

server.listen(port, "127.0.0.1", () => {
  console.log(`API listening on http://127.0.0.1:${port}`);
});
JS
pnpm install
ls -l apps/api/node_modules/@demo

The ls shows that apps/api/node_modules/@demo/shared is a symlink to ../../../../packages/shared. There is no copy: when you rebuild the shared package, the API sees the new code at once. If you publish a package that uses workspace:*, pnpm replaces it with the real version number in the published package.json.

Start the API in your second terminal, from ~/pnpm-monorepo-demo, and leave it running:

Bash
pnpm --filter @demo/api start

Back in the first terminal, ask it for the products:

Bash
curl -s http://127.0.0.1:3001/api/products

Check it worked

The API terminal prints API listening on http://127.0.0.1:3001, and curl returns a JSON array of three products with prices such as "price":"₦18,500.00". Stop the API with Ctrl+C in the second terminal.

Step 5 · Add the web app with a catalog dependency

The web app builds a static HTML page. It uses the shared package and escape-html, a small npm package that turns < and > into safe entities. Both version references are indirect: workspace:* for the shared package and catalog: for escape-html, whose version lives in pnpm-workspace.yaml:

Bash
cat > apps/web/package.json <<'JSON'
{
  "name": "@demo/web",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "build": "node build.js"
  },
  "dependencies": {
    "@demo/shared": "workspace:*",
    "escape-html": "catalog:"
  }
}
JSON
cat > apps/web/build.js <<'JS'
import { mkdirSync, writeFileSync } from "node:fs";
import escapeHtml from "escape-html";
import { formatPrice, sampleProducts } from "@demo/shared";

const items = sampleProducts
  .map((p) => `    <li>${escapeHtml(p.name)}: ${formatPrice(p.priceMinor, p.currency)}</li>`)
  .join("\n");

const html = `<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Shop</title>
<h1>Products</h1>
<ul>
${items}
</ul>
</html>
`;

mkdirSync("dist", { recursive: true });
writeFileSync("dist/index.html", html);
console.log(`Wrote dist/index.html with ${sampleProducts.length} products`);
JS
pnpm install
grep -A4 '^catalogs:' pnpm-lock.yaml

The lockfile has a catalogs section that records what each catalog entry resolved to. When you want a newer escape-html, or a newer TypeScript, you change one line in pnpm-workspace.yaml and run pnpm install. Every package that says catalog: moves together, and no package.json changes, which also means fewer merge conflicts. An existing workspace can move its shared versions into a catalog with pnpm catalog migrate.

Check it worked

The grep prints something like:

Text
catalogs:
  default:
    escape-html:
      specifier: ^1.0.3
      version: 1.0.3

Step 6 · Build in dependency order with -r and --filter

Delete any earlier build output, then run the root build script, which is pnpm -r build:

Bash
rm -rf packages/shared/dist apps/web/dist
pnpm build

-r (recursive) runs the script in every workspace package that has one. pnpm sorts the packages by their dependency graph first, so @demo/shared compiles before @demo/web runs a build that imports it. The API has no build script, so it is skipped. Without that ordering the web build would fail on a clean checkout because packages/shared/dist would not exist yet. pnpm cannot guarantee the order if two workspace packages depend on each other in a cycle, and warns about cycles during install.

--filter narrows any command to part of the graph. The three forms you will use most:

Bash
pnpm --filter "@demo/web..." build
pnpm --filter "...@demo/shared" ls --depth -1
pnpm --filter "...^@demo/shared" exec pwd
  • @demo/web... selects the web app and everything it depends on. Use it when you want to build one app and make sure its dependencies are fresh.
  • ...@demo/shared selects the shared package and everything that depends on it: after you change shared code, these are the packages to test.
  • ...^@demo/shared selects only the dependents, without the package itself.

Check it worked

pnpm build runs tsc and then node build.js, which prints Wrote dist/index.html with 3 products. Open apps/web/dist/index.html in a browser: it lists three products with naira prices, and the third reads Phone case <slim>: ₦4,200.00 as text, because escape-html stored the brackets as &lt; and &gt;. The last command prints two folders, apps/web and apps/api, and not packages/shared.

Step 7 · Watch pnpm catch an undeclared dependency

Suppose someone adds an HTML product page to the API and reaches for escape-html, because the web app already uses it. They forget to add it to the API's package.json:

Bash
cat > apps/api/page.js <<'JS'
import escapeHtml from "escape-html";
import { formatPrice, sampleProducts } from "@demo/shared";

export function productPage() {
  const items = sampleProducts
    .map((p) => `<li>${escapeHtml(p.name)}: ${formatPrice(p.priceMinor, p.currency)}</li>`)
    .join("");
  return `<!doctype html><meta charset="utf-8"><title>Shop</title><ul>${items}</ul>`;
}
JS
cd apps/api
node -e 'import("./page.js").then((m) => console.log(m.productPage()))' || echo "import failed"
cd ~/pnpm-monorepo-demo

It fails with ERR_MODULE_NOT_FOUND and Cannot find package 'escape-html', even though escape-html is installed in the repository. pnpm keeps every package in node_modules/.pnpm and links into each project's node_modules only what that project declares. Node.js looks in apps/api/node_modules, then in the folders above it, and finds nothing.

That failure is the point. A package manager that hoists every dependency into one flat root node_modules would let this import work on your laptop, and it would break later when the API is deployed alone or when the web app drops escape-html. pnpm makes it break now. Declare the dependency, using the same catalog entry:

Bash
pnpm --filter @demo/api add escape-html@catalog:
cd apps/api
node -e 'import("./page.js").then((m) => console.log(m.productPage()))'
cd ~/pnpm-monorepo-demo

Check it worked

apps/api/package.json now lists "escape-html": "catalog:" under dependencies, and the import prints a one-line HTML page with Phone case &lt;slim&gt;: ₦4,200.00 in it. pnpm list -r --depth 0 escape-html shows both apps on the same escape-html@1.0.3.

Step 8 · Ship the API on its own with pnpm deploy

A server or a Docker image for the API should not receive the web app, the TypeScript compiler or anything else the API does not need at run time. pnpm deploy copies one package into a new folder with its own node_modules, holding only that package's dependencies. Workspace dependencies such as @demo/shared are copied in too, so the shared package must be built first:

Bash
pnpm --filter "@demo/api..." build
pnpm --filter @demo/api --prod deploy ~/pnpm-demo-api-deploy
ls ~/pnpm-demo-api-deploy ~/pnpm-demo-api-deploy/node_modules

The filter must select exactly one package. --prod skips devDependencies, so TypeScript, which only the shared package's build needed, stays behind. The shared package arrives with only its dist folder and package.json, because its files list says dist.

Run the deployed copy in your second terminal, on another port so it cannot be confused with the earlier server:

Bash
cd ~/pnpm-demo-api-deploy
PORT=3002 node server.js
Bash
curl -s http://127.0.0.1:3002/api/products

In a Dockerfile you would run the same pnpm deploy in a build stage and copy only the deploy folder into the final image.

Check it worked

ls shows package.json, server.js, page.js and a node_modules folder holding @demo and escape-html, with no typescript. The server prints API listening on http://127.0.0.1:3002, and curl returns the same three products as before. Stop it with Ctrl+C.

Step 9 · Clean up

Stop any API still running in the second terminal with Ctrl+C. Then remove the demo repository and the deploy folder. pnpm stays installed, and its store keeps the downloaded packages for your next project:

Bash
cd ~
rm -rf ~/pnpm-monorepo-demo ~/pnpm-demo-api-deploy

To reclaim the space the store uses for packages that no project links to any more, run pnpm store prune.

Check it worked

ls ~ no longer lists pnpm-monorepo-demo or pnpm-demo-api-deploy.

Next steps

As a monorepo grows, build tools such as Turborepo and Nx sit on top of pnpm workspaces and cache task results, locally and shared across CI runs, so a build whose inputs have not changed is skipped. Add one when builds start to feel slow, not before.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.