The axios SyntaxError: cannot use import statement outside a module means you import axios as an ES module in code the runtime treats as plain script.
Axios SyntaxError: Cannot Use Import Statement Outside A Module Fix Explained
This message shows that axios is loaded with modern import syntax while your runtime still treats that file, or axios itself, as classic CommonJS script code.
Your console usually prints a stack trace that points into node_modules/axios or your own file that says import axios from "axios". The runtime tries to wrap that code in a CommonJS loader, then stumbles on the first import line and throws the SyntaxError instead of running your tests or app.
In plain terms, axios since version 1 uses ES module entry points by default, while many Node setups, Jest configs, and old toolchains still assume CommonJS. When those two styles meet without clear configuration, you see the axios syntaxerror: cannot use import statement outside a module again and again during runs.
That mental model keeps the error less mysterious during debugging.
Why This Import Statement Error Shows Up With Axios
JavaScript now has two module systems that do not mix automatically. ES modules rely on import and export, while CommonJS relies on require and module.exports. Axios 1.x exposes modern module entry points, so your tools must know how to treat that package.
When Node or Jest treats a file as CommonJS, it wraps code in a loader function and expects only require calls. If that wrapper finds an import at the top of axios, it throws the familiar SyntaxError. The same thing happens in browser builds if a script tag loads code as a normal script instead of a module.
Most projects hit this bug in one of three places: a Node script that imports axios without turning on module mode, a Jest test run that skips transforming axios from node_modules/axios, or a bundler config that treats some axios file as plain script instead of module code.
Once you see which side assumes CommonJS, the pattern clicks.
Quick Checks Before You Change Your Axios Setup
Before you start rewriting imports, run through a short list. This often shows where the mismatch sits and saves time.
- Check the stack trace — Read the first file path in the error output and note whether it points to your own test file, a built bundle, or
node_modules/axios. - Confirm your axios version — Run
npm ls axiosor peek atpackage.json. Axios 1.x ships with ES module entry points, while old 0.27 builds behave differently. - Check your module type flag — Open
package.jsonand see whether there is a"type": "module"field. That flag makes Node treat.jsfiles as ES modules. - Check file extensions — In Node,
.mjsand.cjssignal module style. A mismatch between extension andpackage.jsonoften triggers this axios SyntaxError. - Inspect your Jest config — If the failure appears only during tests, skim
jest.config.jsor the config block inpackage.jsonand see whether axios is excluded from transforms.
These quick checks narrow the scope to either runtime module mode, test tooling, or bundler setup. Once you know where the conflict lives, picking the right fix for Axios SyntaxError: cannot use import statement outside a module becomes far easier.
Clear logs make pattern spotting simple.
Fixing Axios Import Statement Outside A Module In Node
Make Node treat both your code and axios in the same module style. That can mean turning on ES modules for the project, keeping CommonJS and loading axios in a compatible way, or letting a bundler handle the gap.
Here are common fixes that work well in small Node apps and larger back end services that call APIs with axios.
Switch The Project To ES Modules
New or modern Node projects that already use import in many files benefit from a full switch. In this setup, you tell Node that every .js file is a module.
- Add the module type — In
package.json, add"type": "module"at the top level. - Use standard imports — Keep lines like
import axios from "axios"in your code without changes. - Run Node with normal commands — The usual
node index.jsentry now understands ES module syntax across the project.
Once this flag is in place, Node no longer wraps axios as CommonJS, so the import statement stays valid and the SyntaxError disappears.
Keep CommonJS And Require Axios Safely
Projects that still use require everywhere, or that rely on tools not ready for ES modules, can stay in CommonJS mode and still call axios cleanly.
- Use require syntax — Replace
import axios from "axios"withconst axios = require("axios")in CommonJS files. - Stick to one style per file — Avoid mixing
requireandimportinside the same script, since that reintroduces module mode confusion. - Let bundlers handle extras — If you later adopt a bundler like Webpack or Vite, keep axios imports consistent and let the build process shape the final output.
This pattern keeps the runtime in line with old CommonJS habits while still letting you call axios in a clear way.
Small experiments in a branch keep risk under tight control.
Use .mjs Or .cjs Extensions When You Mix Styles
In Node 18 and later, file extensions hint at module style. A single project can mix .mjs ES modules with .cjs CommonJS files and stay stable.
- Rename module files — Save files that import axios with ES syntax as
client.mjsor similar. - Keep legacy files as .cjs — Files that still use
requirecan move to the.cjsextension to tell Node they stay in CommonJS mode. - Wire entry points carefully — When you call a module from CommonJS, rely on documented interop patterns or a bundler to avoid new SyntaxError messages.
Handling Axios Import Statement Outside A Module In Jest And Other Test Runners
Many developers meet this axios error only inside Jest or other test runners. The app runs during development, while tests fail as soon as they touch a file that imports axios.
The problem comes from Jest treating node_modules as plain CommonJS by default. Modern packages like axios ship ES module bundles that Jest must pass through a transformer such as Babel. Without that extra step, the first import inside axios triggers the SyntaxError.
Update Jest And Let It Handle ES Modules
Newer Jest versions handle ES modules more smoothly. In many cases, a version bump plus a small config change clears this axios SyntaxError quickly.
- Upgrade Jest — Move to Jest 29 or later so that ES module handling is more mature.
- Adjust transformIgnorePatterns — In
jest.config.js, includeaxiosin the list of packages that Babel transforms instead of skipping. - Use Babel with Jest — Ensure
babel-jestis set up so Jest can transpile axios along with your own source files.
Once Jest treats axios code as a module and runs it through a transformer, the SyntaxError rarely appears again.
Mock Axios In Tests Instead Of Importing The Real Module
Many unit tests do not need the real HTTP client at all. You can mock axios and remove the module style mismatch from the hot path.
- Create a manual mock — Add a
__mocks__/axios.jsfile that exports the functions your tests expect. - Call jest.mock — At the top of a test file, call
jest.mock("axios")so the runner swaps in your stub instead of loading the real axios build. - Keep mocks in sync — When you add axios usage in code, expand your mock to match the shape instead of importing axios directly in tests.
This pattern removes axios internals from test runs, so Jest no longer trips over the import statement outside a module.
Run Tests In A Fully ES Module Project
If your app already uses ES modules everywhere, align Jest with that plan instead of bending axios back toward CommonJS.
- Set type to module — Keep
"type": "module"inpackage.jsonand write tests withimportsyntax. - Use the node test context — Configure Jest with a runtime that handles ES modules cleanly.
- Avoid mixed syntax in helpers — Update helper files and setup scripts that still use
requireso Jest sees a single module style.
Axios SyntaxError: Cannot Use Import Statement Outside A Module In Browser Builds
This message can also show up in browser consoles during local development. In that case, axios is usually bundled by a tool like Vite, Webpack, or Rollup, and the browser only sees the final build.
The browser shows the SyntaxError when a compiled bundle or a script tag uses import in a script that the browser treats as plain inline script instead of a module. That often traces back to a missing type="module" attribute or a bundler config that outputs a plain script but still leaves axios imports unchanged.
Modern bundlers know how to handle axios ES modules, so the fix usually lives in HTML setup or an old config preset. A small change in entry tags or output targets often clears the axios SyntaxError: cannot use import statement outside a module in browser builds.
| Runtime | Typical Symptom | First Fix To Try |
|---|---|---|
| Node Script | Stack trace points into axios when starting a server script. | Add "type": "module" or switch axios imports to require. |
| Jest Tests | Error appears only during unit tests that import axios. | Upgrade Jest and let Babel transform axios, or mock axios. |
| Browser Build | Console shows the SyntaxError on page load. | Ensure entry scripts use type="module" or refine bundler output. |
Preventing This Axios Import Error In New Projects
Pick one module style early for each project, set tooling to match that choice, and treat axios like any other dependency that follows the same rules.
- Decide on ES modules or CommonJS — Write new code in a single style and keep that style consistent in entry points, helpers, and tests.
- Align tools with your choice — Configure Node, Jest, bundlers, and linters to understand that style, with clear
typeflags and file extensions. - Pin axios versions carefully — Before bumping axios to a new major release on older stacks, test in a branch to see whether module entry points change.
- Keep configs under version control — Commit changes to
package.json, Jest config, and bundler files so the team can track shifts in module behavior. - Add smoke tests — Set up a small test that imports axios and runs a simple request so that CI catches module errors soon after upgrades.
With a clear module story and consistent tool settings, you rarely see axios syntaxerror: cannot use import statement outside a module again. When it does appear, a quick check of module type flags, file extensions, and test transforms is usually enough to bring axios back to a clean, predictable import state for you.
