# Replace Axios With Native fetch in a Node.js Library

Yes. An agent rewrites each Axios call to fetch, restores the status and timeout behaviour Axios gave for free, and fixes the HTTP mocks so tests stay offline.

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

## What the agent does

Node has had a global `fetch` since version 18, and a small library that only makes GET requests can drop its one runtime dependency by using it. The agent begins with an inventory, because Axios does several things implicitly that `fetch` does not. In a package like palmerabollo/node-isbn, `package.json` has `axios` `^0.21.1` as the only dependency and `mocha` and `nock` `^9.0.13` for tests. `index.js` calls `axios.request(requestOptions)` in four resolvers, one each for Google Books, Open Library, WorldCat and ISBNdb. Every call merges `defaultOptions`, which sets `timeout: 5000`, with whatever options the caller passed to `isbn.resolve`, and the ISBNdb one adds an `Authorization` header from `process.env.ISBNDB_API_KEY`.

Three behaviours have to be rebuilt by hand. Axios rejects the promise on a non-2xx status, so the `if (status !== 200)` check in each resolver never saw a 500; `fetch` resolves on any status, and that check becomes the only thing standing between an error page and `response.json()`. Axios parses JSON on its own; `fetch` needs the explicit call. And `timeout` becomes `signal: AbortSignal.timeout(ms)`, which rejects with a `TimeoutError` instead of Axios's error object. The agent writes one `_getJson` helper that does all three and uses it in the four places. While there it fixes a message that was always wrong: two resolvers destructure a `statusCode` field that an Axios response does not have, so their error text could only ever read `wrong response code: undefined`.

The larger risk is in the tests, and the agent checks it before trusting a green run. nock 9 patches Node's `http` module. `fetch` does not go through that module, so after the rewrite the old mocks intercept nothing and the suite makes real requests. Half the tests then fail on mocha's two second limit or on a `401` from the live ISBNdb API, and the other half still pass, because they only assert that some error came back. The agent upgrades nock to a release that intercepts `fetch`. It picks the newest one the test file can load: `test/spec.js` uses `require`, and with the latest major that fails with `TypeError: nock is not a function`, so it stays on the last major that `require` returns as a function.

The new nock also changes how delays work. The tests used `.socketDelay(10000)`, which made the old stack report a timeout at once. That method is gone, and its replacement really waits, so a test that queues three slow providers against a five second default cannot finish inside mocha's limit. The agent scales the delays down to milliseconds, passes a short `timeout` option in the timeout tests, and adds `afterEach(() => nock.cleanAll())` so an unused interceptor cannot answer the next test. It runs the suite with outbound network blocked to prove nothing escapes.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Replace axios with the fetch built into Node.js in this package and remove the dependency. First list every axios call with the options it passes, and every axios feature the code relies on without saying so: rejection on non-2xx status, automatic JSON parsing, timeout, baseURL, params, default headers, interceptors, and the shape of the error callers catch. Read the README for options the package lets its own callers pass through to axios and list which of them you will still honour; do not silently drop one. Run the test suite and npm audit first and save both outputs. Write one small helper that wraps fetch and restores what the code needs: throw on a status the old code treated as an error, parse JSON, apply the timeout with AbortSignal.timeout, and pass headers. Keep the package's public functions, callback and promise forms, and error messages the same unless a message was provably wrong, and say which. Then check the tests' HTTP mocking before believing them. Find the mocking library and its version and determine whether that version intercepts fetch. Prove it: run the suite with outbound network blocked (for example nock.disableNetConnect in a root hook, or an unreachable proxy) and report any test that tried to reach a real host. If the mocks do not intercept fetch, upgrade the mocking library to the newest release the test files can load with their current module system, replace removed methods, and adjust delay-based tests so they finish inside the test runner's timeout without weakening what they assert; add cleanup of unused interceptors between tests. List each test whose assertion only checks that an error exists, because those pass for the wrong reason when mocking breaks. Set engines.node in package.json to the lowest version that has global fetch and AbortSignal.timeout, and update any README line that promises older versions. Run the suite again offline and run npm audit again. Open a pull request with both sets of 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

A pull request that changes `index.js`, `test/spec.js`, `package.json`, the lockfile if there is one, and one line of the README. `axios` leaves `dependencies`, which becomes empty; `nock` moves up several majors in `devDependencies`. `npm audit` output from before and after is in the description, and the before list is the reason many teams start this job: the 0.21 line of Axios carries published advisories that the range `^0.21.1` can never leave.

The reviewer reads `_getJson` first. It is short, and every resolver now depends on it for status handling. They check that a caller's `timeout` option still overrides the default and that the ISBNdb header is still sent. Then they read the test diff with the agent's notes beside it: which delays were scaled, which tests received an explicit timeout, and the list of tests that assert only `err != null`. The agent reports that list and does not rewrite those assertions, since tightening them is a separate decision about what the library promises.

Two compatibility notes are stated plainly. The README says the module supports Node.js 6 and greater; global `fetch` needs 18, so `engines` is added and the sentence changes, which makes this a breaking release for anyone on an older runtime. And callers who passed other Axios options through `isbn.resolve`, such as a proxy or an agent, lose them; the description lists what is still honoured.

## Run it on every new Axios advisory

Security advisories are what put this job on a calendar. If your scanner can call a webhook with an `Authorization: Bearer` header, add an automation with this prompt and a `webhook` trigger in the Project and point the scanner at the trigger's URL; where it cannot set that header, a small handler on your server receives the scanner's event and forwards it. The event body is added after the prompt as data. Send an `Idempotency-Key` header to the trigger's URL so a redelivered alert starts nothing new.

For a planned sweep, start one run per package from a script with `POST /o/{org}/sessions` and this body. Each answers `202`; a `request_id` that is a UUID v5 of the repository name makes the script safe to rerun.

## Why run it on Rush?

The failure this job invites is tests that reach the internet. On a laptop that looks like a slow but mostly green run, and a real API key in the environment can make it greener still. The agent's sandbox has no such key, and the run blocks outbound requests during the suite on purpose, so a mock that does not intercept shows up as a named failure. The first broken run, with its `401` from a live host, stays in the session's transcript as the evidence for upgrading the mocking library.

The work is also a chain of small experiments: try the newest nock, read the `TypeError`, step back one major, find the removed method, rescale the delays. Each step is a command and its output, kept in order. A reviewer can follow why the pull request touches the tests more than the source, which is the first question anyone asks of a dependency removal.

## Frequently asked questions

### Does fetch throw on a 404 or 500 the way Axios does?

No. `fetch` rejects only when the request itself fails, for example on a network error or an abort. A 404 or 500 resolves normally with `response.ok` set to false. Code that relied on Axios rejecting has to check the status and throw, which is what the helper the agent writes does.

### How do I set a timeout with fetch?

Pass `signal: AbortSignal.timeout(ms)` in the options. When the time is up the promise rejects with an error whose `name` is `TimeoutError`. A caller that inspected Axios's `code` for `ECONNABORTED` needs to check the name instead.

### Why did my nock tests start hitting the real network?

Older nock releases intercept the `http` and `https` modules, and Node's `fetch` uses a different client underneath. Requests made with `fetch` pass straight through those mocks. Upgrade to a nock release that supports `fetch`, and run the suite once with network access blocked to confirm every request is caught.

### Is it worth removing Axios at all?

For a library that makes a few simple requests, usually yes: one less dependency for your users to audit and update. For an application that leans on interceptors, automatic retries, upload progress or a shared configured instance, the replacement code can outgrow the saving. The agent's inventory at the start shows which case you are in before any code changes.

## More Axios jobs

- [Upgrade axios 0.x to 1.x in a React App](https://getrush.ai/run/upgrade-axios/axios/)
- [Add Request Timeouts to an Axios API Client](https://getrush.ai/run/add-request-timeouts/axios/)
- [Add Retry Logic to a Shared Axios Client](https://getrush.ai/run/add-retry-logic/axios/)

## More jobs like this: Upgrade dependencies weekly

- [Migrate From babel-eslint to @babel/eslint-parser](https://getrush.ai/run/migrate-babel-eslint-to-babel-eslint-parser/babel-eslint/)
- [Migrate a Go Project From Blackfriday to goldmark](https://getrush.ai/run/migrate-blackfriday-to-goldmark/blackfriday/)
- [Migrate From Bluebird to Native Promises in a Node.js Library](https://getrush.ai/run/migrate-bluebird-to-native-promises/bluebird/)

## 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/)
