Sub topic 10
From assert to with: Migrating Legacy Import Assertions
This chapter assumes you already know the with { type: "json" } syntax and why the type attribute is required. Older codebases, blog posts, and Stack Overflow answers often show a different form, assert { type: "json" }. That form is called import assertions. It was an earlier version of the same feature, and current runtimes reject it. This chapter explains where assert came from, why the language moved away from it, and how to migrate a codebase without breaking anything.
Two Syntaxes, One Feature
The two forms look almost identical:
// Legacy: import assertions (rejected by current runtimes)
// import config from "./config.json" assert { type: "json" };
// Current: import attributes
import config from "./config.json" with { type: "json" };
console.log(config.appName);The attribute object did not change. Only the keyword before it changed. For JSON modules, migrating usually means swapping one word. To migrate safely, though, you need to know where assert can appear, which tools still emit it, and which runtimes accept which form.
Why the Keyword Changed
The keyword change came with a change in meaning.
Under the import assertions proposal, the clause was check-only. The host (the browser or Node.js) fetched and parsed the module the way it normally would. Then it checked whether the result matched the assertion and threw an error if it did not. The assertion was not allowed to change how the module was loaded or interpreted.
Browsers could not work within that rule. To fetch a JSON module correctly, a browser has to know before sending the request that it expects JSON. That knowledge affects the request's Accept header, its fetch destination, and which Content Security Policy directive applies. So type: "json" was already changing how the module loaded, which an assertion was not allowed to do.
In 2023 the proposal was revised. The clause became import attributes, which are allowed to affect loading, and the keyword became with to signal the new meaning. The proposal reached Stage 4 in October 2024 and is part of ECMAScript 2025.
A Parsing Quirk That Went Away
assert is not a reserved word, so the old grammar forbade a line break between the module specifier and assert. Without that rule, the parser could not distinguish the clause from a separate statement. with is a reserved word, so the new grammar has no such restriction:
// Valid with the new syntax: line break before `with`
import config from "./config.json"
with { type: "json" };
console.log(config.version);If a code formatter produced single-line assert clauses to work around the old restriction, you can reformat them freely after migrating.
Where assert Appears
Search for every place an import clause can appear, not only static imports.
| Form | Legacy | Current |
|---|---|---|
| Static import | `import c from "./c.json" assert { type: "json" };` | `import c from "./c.json" with { type: "json" };` |
| Side-effect import | `import "./c.json" assert { type: "json" };` | `import "./c.json" with { type: "json" };` |
| Re-export | `export { default as c } from "./c.json" assert { type: "json" };` | `export { default as c } from "./c.json" with { type: "json" };` |
| Dynamic import | `import("./c.json", { assert: { type: "json" } })` | `import("./c.json", { with: { type: "json" } })` |
The dynamic form is the easiest to miss. In a dynamic import, assert is a property name in the options object, not a keyword. A search for assert { will not find it.
async function loadLocale(lang) {
// Legacy: { assert: { type: "json" } }
const module = await import(`./locales/${lang}.json`, {
with: { type: "json" }
});
return module.default;
}
const messages = await loadLocale("en");
console.log(messages.greeting);Runtime and Tool Support
What a migration breaks depends on which runtimes and tools you support.
| Environment | `assert` | `with` |
|---|---|---|
| Chrome / Edge | Shipped in 91, removed in 126 | Since 123 |
| Firefox | Never shipped | Since 138 |
| Safari | Not needed for migration | Since 17.2 |
| Node.js | 16.14 / 17.1 through 21.x | 18.20, 20.10, 21.0 and later |
| Node.js 22+ | Syntax error | Supported |
| Deno | Removed in 2.0 | Supported |
| TypeScript | Since 4.5, deprecated in later releases | Since 5.3 |
Two practical conclusions follow from this table:
- Node.js 18.20+ and 20.10+ accept both forms, so you can migrate the source first and upgrade the runtime afterwards. On those versions,
assertmay print a deprecation warning, which helps you find files you missed. - Node.js 22 and current Chromium reject
assertwith aSyntaxErrorwhen the module is parsed. Because the whole module graph is parsed before any code runs, one leftoverassertin a dependency stops the entire application from starting.
Migrating a Codebase
Step 1: Find Every Occurrence
A recursive search finds both the keyword form and the options-object form:
grep -rnE "assert[[:space:]]*\{[[:space:]]*type|assert[[:space:]]*:[[:space:]]*\{" --include="*.js" --include="*.mjs" --include="*.ts" --include="*.mts" srcRun it against node_modules too, to find dependencies that need upgrading.
Step 2: Rewrite the Source
For a small project, find-and-replace in your editor is enough. For a larger one, a short Node.js script handles all four forms. It needs Node.js 20.1 or later for readdir with recursive: true.
// migrate-assert.mjs
// Usage: node migrate-assert.mjs src
import { readdir, readFile, writeFile } from "node:fs/promises";
import { join, extname } from "node:path";
const root = process.argv[2] ?? "src";
const exts = new Set([".js", ".mjs", ".ts", ".mts", ".jsx", ".tsx"]);
const rules = [
// import x from "./a.json" assert { ... } and export ... from "./a.json" assert { ... }
[/(from\s*["'][^"']+["']\s*)assert(\s*\{)/g, "$1with$2"],
// import "./a.json" assert { ... }
[/(import\s*["'][^"']+["']\s*)assert(\s*\{)/g, "$1with$2"],
// import("./a.json", { assert: { ... } })
[/(import\s*\([^)]*?,\s*\{\s*)assert(\s*:)/g, "$1with$2"]
];
const entries = await readdir(root, { recursive: true, withFileTypes: true });
let changed = 0;
for (const entry of entries) {
if (!entry.isFile() || !exts.has(extname(entry.name))) continue;
const path = join(entry.parentPath ?? entry.path, entry.name);
const before = await readFile(path, "utf8");
let after = before;
for (const [pattern, replacement] of rules) {
after = after.replace(pattern, replacement);
}
if (after !== before) {
await writeFile(path, after);
changed++;
console.log(`updated ${path}`);
}
}
console.log(`${changed} file(s) updated`);The script uses regular expressions, not a full parser. It can miss unusual formatting, such as a dynamic import whose specifier expression contains a closing parenthesis. Commit your work before running it, review the diff afterwards, and run the search from Step 1 again to confirm nothing is left.
Step 3: Update the Tooling
Source changes alone are not enough if a build step parses or emits the syntax:
- TypeScript: use version 5.3 or later. Recent versions report
assertas deprecated, and under--module nodenextthey report it as an error. That gives you a compile-time check that the migration is complete. - Babel:
@babel/plugin-syntax-import-attributesparseswith. ItsdeprecatedAssertSyntaxoption exists only so that old code keeps parsing during the transition. Remove that option once the migration is done. - Bundlers and linters: current versions of esbuild, Rollup, Vite, webpack, and ESLint parse
with. If an older version fails with an "unexpected token" error atwith, upgrade it.
Step 4: Raise the Minimum Runtime
Once the source contains only with, set your engines field (or your browser support targets) to versions that understand it, for example "node": ">=18.20". That way, users on older runtimes get a clear install-time warning instead of a parse error.
Choosing Between Supporting Both Forms and Committing to with
Old and new runtimes cannot share one static import, because each form is a syntax error to runtimes that do not know it. If you truly must support both Node.js 16 and Node.js 22, your options are:
- Avoid JSON modules and read the file with
fsandJSON.parse. This works on every version. - Ship two builds, each with its own syntax.
- Drop support for runtimes older than Node.js 18.20.
Node.js 16 has reached end of life, so the third option is usually the right one.
Exercise
After upgrading from Node.js 20 to Node.js 22, an app fails at startup with "SyntaxError: Unexpected identifier 'assert'". Your own source contains no assert clauses. What is the likely cause, and how do you fix it?
Show answer
A dependency in nodemodules still ships the legacy import ... assert { type: "json" } syntax. Node.js 22 removed support for it, and because the whole module graph is parsed before execution, the error stops the app from starting. Find the package with a recursive search of nodemodules and upgrade it to a release that uses with. If no such release exists, patch it temporarily, for example with patch-package.
Exercise
Migrate this line to the current syntax: const data = await import(url, { assert: { type: "json" } });. Why would a search for "assert {" miss it?
Show answer
const data = await import(url, { with: { type: "json" } });. In dynamic import, assert is a property name followed by a colon, not a keyword followed by a brace, so the pattern "assert {" does not match it.
Exercise
Under the original import assertions proposal, why could browsers not treat type: "json" as a pure check, and what changed in import attributes to fix this?
Show answer
Assertions were only allowed to verify the module after loading and could not change how it was loaded. Browsers need to know the expected type before the request, to set the Accept header, the fetch destination, and the CSP directive that applies. Import attributes are explicitly allowed to influence loading, and the keyword changed to with to reflect that change in meaning.