# Creating a NodeJS monorepo

I recently wrote about a way to skip repeated rebuilds of internal packages during local development in a monorepo:

%[https://ramblings.nithinrdy.com/p/creating-a-nodejs-monorepo]

I figured I’d take a step back and write about how one would set up a NodeJS monorepo to begin with — or at least, the way I set one up last year.

## **But why a monorepo?**

If you’ve looked up this article you likely already have your own reasons so feel free to skip this section. There are several benefits:

- If you wish to update, let’s say, an API (so you’d have to change an endpoint, and how consumers of the API use said endpoint) — it’s much easier to coordinate such a change with one PR (in a monorepo) as opposed to multiple PRs targeting multiple parts of the application across different repos.
- If you’re using TypeScript in particular, shared types for use across the various parts of the app can really help speed things up during development.
- Helps with centralising your dependencies, so every layer of your app uses the exact same version of everything, a simple way to prevent tiny *version-mismatch* related headaches.
- In my particular case, we already had a relatively-mature Vite React App that served as the main application. I was tasked with constructing a separate public-facing NextJS app. After realising that a lot of the UI used similar (if not the exact same) components, the choice to set up a monorepo became a no-brainer. I was able to pluck out out a huge set of UI components, the styling configuration (Tailwind + PostCSS), icon components, and more into shared packages, leaving the Vite and NextJS apps as consumers of said packages.

The sheer amount of code that I was able to NOT write and instead just re-use was simply… beautiful… *sniff…* sorry where was I? Oh yes, monorepos, let’s create one.

## **What you’ll need**

To keep things consistent with the other article, I’ll stick to the exact same toolset here:

- [*Yarn workspaces*](https://yarnpkg.com/features/workspaces) to manage each of the individual repos as… separate workspaces (you can alternatively use *pnpm*, etc.),
- [*Turborepo*](https://turborepo.dev/docs#what-is-turborepo) to create dependency chains and orchestrate building of the constituent apps and packages,
- [*Syncpack*](https://github.com/JamieMason/syncpack) to ensure packages across repos remain in sync (optional but recommended, super helpful when managing dependencies),

And… that’s about it, the only other things you need are your apps and packages that presumably are all living separately at the moment (or maybe it’s all in one monolithic package, and you wish to [split it into separate app(s) and package(s)](https://docs.npmjs.com/about-packages-and-modules#about-packages) *as* you’re creating the monorepo).

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><p>You will need to uniform-ize the <code>package.json</code> script names by the time we get to the step “<em>3. Adding Turborepo</em>” (for example, you can’t have the <code>dev</code> script be called “<code>start</code>” in one app, and “<code>serve</code>” in another package).<br></p><p>For the sake of this example I’ll generalise all <code>package.json</code> scripts (<code>dev</code> means <code>dev</code>/<code>start</code>/<code>serve</code>/<code>run</code>/<code>whatever-you’ve-named-your-dev-script</code>, and <code>build</code> means <code>build</code>/<code>whatever-you’ve-named-your-build-script</code>, so on).</p></div>
</div>

## **Creating the monorepo**

---

*If you’re enjoying the post, please consider following me (here or on* [*Twitter*](https://x.com/maybe_nithinrdy) *or* [*Bluesky*](https://bsky.app/profile/nithinrdy.com)*!)* :)

---

### **1\. Getting Started**

Let’s start by defining some goals. In my case, I had a single Vite React app and was tasked with creating a NextJS app: I decided to set up a mono-repository for this because they would have had a whole bunch of common components, icons, etc. Aaand.. go!

I envisioned this structure:

- **App 1**: The main Vite React app, depends on packages 1, 2 and 3.
- **App 2**: The NextJS app, depends on packages 1, 2 and 3.
- **Package 1**: Icons used across both apps. No dependencies.
- **Package 2**: Shared UI components (buttons, cards, tiles and the like). Depends on package 1.
- **Package 3**: A shared tailwind-config. No dependencies.

Here’s a visualisation (same scenario as the previous post):

![Apps 1 and 2; packages 1, 2 and 3.](https://cdn.hashnode.com/uploads/covers/69cc43f0e4688e4edd4b7295/ed0c862b-c57d-46d4-8f24-d817aeebf3b5.png align="center")

*Apps 1 and 2; packages 1, 2 and 3.*

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><p><strong>Wait, are you saying the UI package (2) doesn’t depend on the tailwind-config package (3)? Doesn’t the UI need tailwind for styling?</strong></p><p>Well yes, but the tailwind styles and config that the UI requires must come from the consuming parent app itself.</p><p>So even though the two apps and the UI package use tailwind within themselves, only the apps must import the tailwind-config: and then they both use the UI package as needed, letting the package derive the necessary styling <em>from</em> its corresponding parent app.</p></div>
</div>

The folder structure is a good place to start. From the *root*, here’s what I wanted it to look like:

- `apps/`
  - `vite-app/`
  - `next-app/`
- `packages/`
  - `ui/`
  - `tailwind-config/`
  - `icons/`
- `.gitignore`
- `.syncpackrc.json` (*Syncpack* config to maintain package versions)
- `package.json`
- `turbo.json` (or `turbo.jsonc`, `jsonc` allows comments in JSON)
- `yarn.lock`
- [`README.md`](http://README.md)

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><p>Of course, each app/package will have its own <code>package.json</code>, <code>.gitignore</code>, etc. The root ones are to manage the monorepo itself.</p></div>
</div>

### **2\. Project structure and workspaces**

Let’s look at the root `package.json`. This will contain the Yarn-specific monorepo config, global-level commands and stuff like that. Here’s a rough skeleton:

```json
{
  "name": "monorepo", // <-- remember this part, name of the root package
  "version": "0.0.1",
  "packageManager": "yarn@x.y.z",
  "type": "module",
  "private": true,
  // Likely won't need this, optional: https://yarnpkg.com/configuration/manifest#resolutions
  "resolutions": {
    "@types/react": "^a.b.c",
    "@types/react-dom": "^a.b.c",
  },
  "devDependencies": {
    // will contain turbo and syncpack once we add them
  },
  "scripts": {
    // We'll come back to this
  },
  // The important part: this array tells yarn "any package that fits these glob patterns is a workspace in this monorepo."
  // Since I split my packages up as "apps" (2) and "packages" (3), and will be creating such directories
  // to place them in, that's what I've written here.
  "workspaces": [
    "apps/*",
    "packages/*"
  ]
}
```

Let’s start shaping the project. Both apps go into `apps/`, all the packages go into `packages/`.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><p>In case you are also actively splitting a monolith app into apps &amp; packages <em>as</em> you’re crafting this monorepo, it might be easier to create only 1 app and 1 package and get them to work first.</p><p>Then incrementally add the remaining packages (which you will presumably extract from the now-added monolith) afterwards, one-by-one.</p></div>
</div>

1. Create `apps/` and `packages/` in the root of the project.
2. For each separate app/package you wish to have, pick it up as it is and plop it down into the right directory. Now inside the app/package you just placed:
   1. Delete `node_modules/` and `yarn.lock` (or `package-lock.json`).
   2. Change `“name”` in `package.json` to `@<name_of_root_package>/<name_of_app_or_package>` (for example, `@monorepo/my-package`). **Note**: *I like to append* `-app` *to the names of apps because the names appear in various configs, makes it easier to differentiate (so* `editor` *—>* `@monorepo/editor-app`*)*.
3. Repeat for all apps and packages.
4. Wherever a package is imported by an app/package make sure the new name is used, now that the packages all live together. For example, for `vite-app` (now `@monorepo/vite-app`)’s `package.json`:

   ```json
     "devDependencies": {
       "@monorepo/icons": "1.0.0",
       "@monorepo/tailwind-config": "1.0.0",
       "@monorepo/ui": "1.0.0",
       // ...
     }
   ```

   and similarly for the import statements and stuff.
5. Now run a quick `yarn` to re-install all the dependencies and you’re ready to test!

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><p><strong>Wait, why did I have to delete </strong><code>node_modules/</code><strong> and </strong><code>yarn.lock</code><strong> for each file?</strong></p><p>In a monorepo, all packages share a single lockfile and <code>node_modules/</code>, at the root. When you just ran <code>yarn</code>, a new <code>yarn.lock</code> was created at the root, and a new <code>node_modules/</code> was created:</p><ul><li><p>at the root</p></li><li><p>and possibly within each package (these new ones are different from what the packages had before that we deleted)</p></li></ul></div>
</div>

Now here’s the crucial part, **without Turborepo there is no “build orchestration” yet: Yarn doesn’t yet know which app(s) depend on which package(s)**.

We’ll add turborepo in the next step but this means, *for now, if you run* `yarn dev` *on an app it will not work unless you first run* `yarn build` *on all the packages the app depends on, and all the packages that those packages depend on, and so on* (Turborepo will make this a piece of cake… in a bit).

So for now pick an app, go down its dependency chain and, from the bottom, build each package. When you reach the top (i.e. back to the app), run `dev` and now you *should* have the app running!

### **3\. Adding Turborepo**

Make life a million times easier by letting Turbo manage dependency build chains. Turbo will let you

- run a single command (say, `yarn dev` on `vite-app`), and it will take care of preparing the shared package-dependencies before running the app.
- cache the build outputs of the shared packages, making repeated builds a breeze (only rebuilds changes)

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><p>Now you should really, <em>REALLY</em>, read <a target="_self" rel="noopener noreferrer nofollow" class="cursor-pointer" href="https://turborepo.dev/docs/crafting-your-repository/structuring-a-repository" style="pointer-events: none;">the official guide</a> and take your time with it, but I’ll include a brief (but very linear) guide here.</p></div>
</div>

To start, [install Turborepo](https://turborepo.dev/docs/getting-started/add-to-existing-repository#adding-turborepo-to-your-repository), both globally (`curl -fsSL` [`https://turborepo.dev/install`](https://turborepo.dev/install) `| sh`) and in the root (`yarn add turbo --dev --ignore-workspace-root-check`). Then add `turbo.json`. Finally add `.turbo` to `.gitignore` (turbo stores its cache here).

Once again, [the official guide](https://turborepo.dev/docs/crafting-your-repository/configuring-tasks) is the best for this, but here’s what the config looks like:

```json
{
  "$schema": "https://turborepo.dev/schema.json",
  // Lets you configure a “task” (property-key = name of task).
  // Task is an entry in "scripts" of the "package.json" of apps/packages.
  "tasks": {
      // Task "build" means it applies to every single “build” script
      // in any package.json.
      // You can target a specific package’s task with <package_name>#<task_name>
      // (like @monorepo/vite-app#build).
    "build": {
      // dependsOn means before running "build" on any package P, first run "build" on all packages
      // that P depends on, then come back and P's "build"
      "dependsOn": ["^build"], // <-- obviously doesn't have to be the same ("build"), can be any task 
      
      // these paths are checked to see if something changed when this task was run
      // if yes, the parent of this task is re-triggered
      // (if A depends on B: whenever B's "outputs" change, A is rebuilt)
      "outputs": ["dist/**"]
    },
    "dev": {
      "persistent": true, // long-running task (such as "dev")
      "cache": false // wouldn't want to cache "dev" task
    }
  }
}
```

For our example scenario, we’d have something like this:

```json
{
  "$schema": "https://turborepo.dev/schema.json",
  "tasks": {
    "@monorepo/vite-app#build": {
      // inputs = "whenever these files change, this task is rerun"
      // $TURBO_DEFAULT$ = every file that isn't .gitignored
      "inputs": ["$TURBO_DEFAULT$", ".env"],
      "outputs": ["dist/**"],
      "dependsOn": ["^build"]
    },
    "@monorepo/next-app#build": {
      "inputs": ["$TURBO_DEFAULT$", ".env"],
      "outputs": [".next/**"],
      "dependsOn": ["^build"]
    },
    "@monorepo/ui#build": {
      "outputs": ["dist/**"],
      // Didnt have to target @monorepo/icons since thats the only dependency for
      // @monorepo/ui, so Turbo already knows, but just for the sake of example.
      "dependsOn": ["@monorepo/icons#build"]
    },
    "@monorepo/icons#build": {
      // no dependencies, no dependsOn needed
      "outputs": ["dist/**"]
    },
    "@monorepo/tailwind-config#build": {
      // "outputs" doesnt necessarily need to track built artefacts
      // it can also track only static files, meaning it'll never change, which is fine
      "outputs": ["theming.css", "postcss.config.js"]
    },
    "@monorepo/vite-app#dev": {
      // "#dev" depends on "build" because built artefacts exported by the
      // packages are used when importing, so build must run at least once
      // to guarantee they exist
      "dependsOn": ["^build"],
      "persistent": true,
      "cache": false
    },
    "@monorepo/next-app#dev": {
      "dependsOn": ["^build"],
      "persistent": true,
      "cache": false
    },
  }
}
```

Now you can [run the required turbo tasks](https://turborepo.com/docs/crafting-your-repository/running-tasks) and enjoy the benefits Turbo brings! For example:

```shell
# NOTE: For all these, the tasks that are in the dependency chain are also run
# (in bottom-up order), that's the whole point of Turbo

turbo run dev # run dev task for all apps/packages that have it
turbo run dev --filter=@monorepo/vite-app # run dev for vite-app
turbo run build --filter=@monorepo/next-app # build next app
```

---

Remember this part when we were discussing the root `package.json` in “*2\. Project structure and workspaces*”?

```json
  "scripts": {
    // We'll come back to this
  },
```

To make things easier, add the most commonly run commands here:

```json
  "scripts": {
    "dev:vite": "turbo run dev --filter=@monorepo/vite-app",
    "dev:next": "turbo run dev --filter=@monorepo/next-app",
    "build:vite": "turbo run build --filter=@monorepo/vite-app",
    "build:next": "turbo run build --filter=@monorepo/next-app",
    // ...
  },
```

And you can simply run, for example, `yarn dev:vite` from the root, and so on.

### **4\. Adding Syncpack (optional, but highly recommended)**

This will let you enforce consistent versioning for any package that are common across the monorepo, which’ll help you prevent [unforeseen consequences](https://youtu.be/r-eMVfiT8_c?si=9u8YKeJt3XgjvRM0) due to version-mismatch bugs (pain to debug).

Simply add *Syncpack* as a root dev dependency (`yarn add syncpack --dev --ignore-workspace-root-check`) and add a basic `.syncpackrc.json` config, for example:

```json
{
  "$schema": "./node_modules/syncpack/dist/schema.json", // valid at the time of writing
  "versionGroups": [
    {
      "dependencies": ["@monorepo/**"],
      "label": "Internal Packages"
    },
    {
      "dependencies": ["@types/**"],
      "label": "Type Definitions"
    },
    {
      "dependencies": ["**"],
      "label": "Rest"
    }
    // ...
  ]
}
```

and run `syncpack lint` (you can check out syncpack’s reference [here](https://www.npmjs.com/package/syncpack)). You can add syncpack commands to the root `package.json` like we did with the `turbo run` commands. You can also add them to something like [*Husky*](https://github.com/typicode/husky) to run the check(s) pre-push or something like that.

## **Finishing up**

### **1\. Adding a new app/package**

Any package with path matching the root `package.json`’s `workspaces` glob pattern array will be tracked by yarn. To see the list of existing workspaces run `yarn workspaces info`. To create a new app/package, simply place a package inside `apps/`/`packages/`, i.e. a directory with `package.json` with at least the following:

```json
{
  "name": "@monorepo/<name>",
  "version": "x.y.z",
  // ...
}
```

[and then tie it up with Turborepo and that's all](https://turborepo.com/docs/crafting-your-repository/creating-an-internal-package)!

### **2\. Installing an NPM package within a specific app/package**

```shell
# If the dependency is already in use by a different workspace,
# try to install the same version as what's used everywhere else.
yarn workspace <workspace_name> add <package_name> # Run from root
```

### **3\. Installing an NPM package at the root**

```shell
yarn add abc --ignore-workspace-root-check # Run from root
```

### **4\. While developing, I’m having to wait for my shared package(s) to fully rebuild every time I make a tiny change**

Read my previous post!

%[https://ramblings.nithinrdy.com/p/creating-a-nodejs-monorepo]

---

*Thanks for reading! If you enjoyed this I’d really appreciate a follow (here or on* [*Twitter*](https://x.com/maybe_nithinrdy) *and* [*Bluesky*](https://bsky.app/profile/nithinrdy.com)*)!*
