# Migrate a Node.js App from CommonJS to ESM

Yes. An agent turns every require into an import, keeps Grunt and the Cypress plugin on CommonJS where they must stay, and proves the app still runs end to end.

[Run this on Rush](https://cloud.getrush.ai/run/migrate-commonjs-to-esm/nodejs/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent starts by reading how modules are wired today. In an Express app shaped like OWASP/NodeGoat, package.json has no `type` field, `main` is server.js, and the start script is `node server.js`. server.js requires express, serve-favicon, body-parser, express-session, consolidate, swig, `MongoClient` off the mongodb 2.x package, http, marked, `./app/routes` and `./config/config`, and uses `__dirname` three times: for the favicon path, the views directory and the static assets directory. app/routes/index.js requires nine handler modules and ends in `module.exports = index`; each handler such as app/routes/session.js pulls `UserDAO` and `AllocationsDAO` off their DAO modules with `require("../data/user-dao").UserDAO`, and each DAO ends in `module.exports = { UserDAO }`. There are 34 `require` calls across app/routes and app/data, every one of them without a file extension, which ESM will not resolve.

Two files decide how hard the migration is. config/config.js builds a path from `process.env.NODE_ENV` and requires `config/env/<name>.js` at runtime; a dynamic `require` has no direct ESM equivalent that also works on Node 12, so the agent imports all.js, development.js, production.js and test.js statically and picks one by name. Gruntfile.js is `module.exports = function(grunt)` and calls `require.resolve("chromedriver")` inside a task, and Grunt loads it with `require`, so it is renamed to Gruntfile.cjs and the `test`, `precommit` and `db:seed` scripts pass `--gruntfile Gruntfile.cjs`. The Cypress 3 plugins file in test/e2e/plugins/index.js is also loaded with `require` by Cypress, and it reads `port` and `hostName` from config/env/all.js; once that file is an ES module the plugin cannot require it, so the plugin becomes index.cjs, named in cypress.json, and reads `PORT` with the same default of 4000 that all.js uses. The support and commands files under test/e2e/support are browser code that Cypress bundles itself and need no change.

Then the mechanical pass. package.json gets `"type": "module"`. Every `require` becomes an `import` with its `.js` extension, `module.exports = X` becomes `export default X` and `module.exports = { UserDAO }` becomes a named export, so `import { UserDAO } from "../data/user-dao.js"` reads as before. `MongoClient` is taken off the mongodb default import, because a CommonJS package built before named-export detection may not expose it as a named import. `__dirname` in server.js is replaced with `path.dirname(fileURLToPath(import.meta.url))`, and the `"use strict"` pragmas go, since modules are strict by definition. artifacts/db-reset.js keeps its shebang and gets the same treatment, because docker-compose.yml runs it before `npm start`. .jshintrc gets `"module": true` so jshint 2.12.0 accepts `import` and `export`, and its `strict` setting changes from `true` to `"implied"` so the removed pragmas are not flagged.

The last change is the Node range. e2e-test.yml runs on 10.x, 12.x and 14.x; unflagged ES modules arrived in 12.17, so 10.x leaves the matrix and package.json gets an `engines` field saying so. The Dockerfile's node:12-alpine stays. To prove it, the agent runs `npm ci`, starts a mongo container the way the workflow does, runs `npm run db:seed`, starts the app with `NODE_ENV=test npm start`, and runs `npm run test:ci`, the Cypress suite of thirteen specs under test/e2e/integration, plus `npx jshint .` as lint.yml does and a `docker build`. It also notes in the pull request that `grunt test` points mochaTest at test/unit/*.js, a directory that does not exist, so there are no unit tests to convert and mocha 2.4.5 would need an upgrade before any ESM test file could run.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Migrate this Node.js app from CommonJS to ES modules. Read package.json, server.js, config/config.js, config/env/*.js, app/routes/*.js, app/data/*.js, artifacts/db-reset.js, Gruntfile.js, .jshintrc, cypress.json, test/e2e/plugins/index.js, Dockerfile, docker-compose.yml, Procfile and the workflows under .github/workflows first, and list every require, module.exports, __dirname and dynamic require you find. Add \"type\": \"module\" to package.json, convert every require to an import with an explicit .js extension, turn module.exports into default or named exports so existing import names stay the same, and replace __dirname with import.meta.url. Replace the dynamic environment require in config/config.js with static imports of the env files chosen by NODE_ENV. Keep Gruntfile and the Cypress plugins file on CommonJS by renaming them to .cjs and pointing the npm scripts and cypress.json at them; the Cypress plugin must not import an ES module. Update .jshintrc so jshint accepts modules and drop the use strict pragmas. Drop Node 10 from the CI matrix and add an engines field. Then run npm ci, start MongoDB, run npm run db:seed, start the app with NODE_ENV=test, run npm run test:ci, run npx jshint . and docker build, and open a pull request that lists each file changed, the Node range, and the test and lint output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request on its own branch that touches package.json, server.js, config/config.js, the four files under config/env, the ten files under app/routes, the seven DAOs under app/data, artifacts/db-reset.js, .jshintrc, cypress.json, the e2e workflow, and renames Gruntfile.js to Gruntfile.cjs and test/e2e/plugins/index.js to index.cjs. The description lists the imports that changed shape, names the two files that stayed CommonJS and why, and states the new Node floor.

The evidence is the sandbox run: `npm run test:ci` output from the Cypress specs against a seeded MongoDB, the jshint pass over the module syntax, and the Docker image building from node:12-alpine. The description quotes those, not a summary of them, and says plainly that no unit tests exist to run under `grunt test`.

Before merging, a reviewer checks that every relative import carries its extension, that `MongoClient` is read off the default import rather than a named one, and that the Cypress plugin's base URL matches what the workflow starts. If the team also wants mocha upgraded so ESM unit tests can be written, that is a follow-up on the same session, with the branch and node_modules still in place.

## Run it on every repository still on CommonJS

This is a change you start and walk away from: one `POST /o/{org}/sessions` with this prompt and the repository in `resources`, sent from the terminal before the laptop closes. The run clones the repository, installs, converts, runs the suite and opens the pull request without anyone watching. The sandbox parks with its disk when the turn ends, so a follow-up such as `also convert the Cypress plugin to read config from an env file` wakes it with node_modules and the branch intact.

A team with several Node services sends the same body once per repository, one run each, and each run reads that service's own `require` graph. Give the API key a `webhook_url` and Rush posts `run.completed` or `run.failed` with the `session_url` when each turn ends, so the pull request links collect in one place. Send a `request_id` with each request so a retried POST returns the run it already started.

## Why run it on Rush?

An ESM migration fails in the places a grep does not show: a dynamic require, a tool that loads your file with `require`, a CommonJS package whose named exports the loader cannot see, a `__dirname` in a path that only breaks at runtime. The only honest check is to start the app and drive it, which here means a MongoDB, a seed script and a Cypress run. The agent does all of that in its own sandbox before the pull request exists, so the diff arrives with the suite's output rather than a promise that it should work.

The run's record is the review guide. The transcript shows each file read, the moment the agent found that Cypress loads its plugin with `require`, and the exact commands with their output. A reviewer who wants Node 12 dropped too, or the mongodb driver upgraded while the app is open, says so in a follow-up and the parked sandbox makes the change with the tests already passing.

## Frequently asked questions

### Why do Gruntfile.js and the Cypress plugin stay CommonJS?

Because Grunt and Cypress 3 load those files with require, not import. Renaming them to .cjs keeps them loadable once package.json says type module, and the npm scripts pass --gruntfile Gruntfile.cjs while cypress.json names plugins/index.cjs. The plugin stops reading config/env/all.js, which becomes an ES module, and reads PORT with the same default instead.

### How is the dynamic require in config/config.js handled?

With static imports of all four env files and a lookup by NODE_ENV. Top-level await would also work but needs Node 14.8, and the matrix still runs 12.x; static imports keep the same behaviour on every version the workflow tests, and an unknown NODE_ENV falls back to development as before.

### Will named imports from mongodb, express and the other packages work?

Default imports always do. The agent takes MongoClient off the mongodb default import rather than relying on named-export detection for a 2.x CommonJS build, and does the same anywhere a package's named import fails under node, which the first npm start would show.

### Does Node 10 have to go?

Yes. Modules without a flag need Node 12.17 or later, so 10.x leaves the e2e matrix and package.json gains an engines field. The Dockerfile already builds from node:12-alpine and keeps doing so.

### What about the unit tests?

There are none to migrate: grunt test points mochaTest at test/unit/*.js, which does not exist, so the e2e Cypress suite is the proof. The pull request says that mocha 2.4.5 cannot load ESM test files, so adding unit tests later means upgrading mocha first.

## More Node.js jobs

- [Migrate Cypress Tests to Playwright in a Node.js App](https://getrush.ai/run/migrate-cypress-to-playwright/nodejs/)
- [Replace Grunt With npm Scripts in a Node.js App](https://getrush.ai/run/migrate-grunt-to-npm-scripts/nodejs/)
- [Run a Security Audit on a Node.js App](https://getrush.ai/run/security-audit/nodejs/)

## More jobs like this: Hand off a long task

- [Migrate a Create React App Project to Vite](https://getrush.ai/run/migrate-create-react-app-to-vite/create-react-app/)
- [Replace dotenv With Node's --env-file Flag in an Express App](https://getrush.ai/run/migrate-dotenv-to-env-file/dotenv/)
- [Migrate Enzyme Tests to React Testing Library](https://getrush.ai/run/migrate-enzyme-to-testing-library/enzyme/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
