Every Node.js service eventually leaks something: a temp directory that never got deleted, a file handle left open after an exception, a lock that nobody released. The JavaScript using keyword (explicit resource management) fixes this class of bug by tying cleanup to the block a resource lives in. In this tutorial we will build one small thing end to end, a report job that creates a temp directory, writes a file and times itself, and we will let using and await using do all the cleanup.
Why the JavaScript using keyword beats try/finally
Here is the usual shape of the code without the new syntax:
import { mkdtemp, rm, open } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
async function oldWay(rows) {
const dir = await mkdtemp(join(tmpdir(), 'job-'));
let fh;
try {
fh = await open(join(dir, 'report.csv'), 'w');
await fh.write(rows.join('\n'));
} finally {
await fh?.close(); // if this throws, rm below never runs
await rm(dir, { recursive: true, force: true });
}
}
The let fh declared outside the try, the optional chaining and the fact that one failing cleanup step skips the next are all accidents waiting to happen. The JavaScript using keyword removes them: each resource is released where it was declared, in the right order, even when another release fails.
Step 1: Check your runtime and set up the project
The feature is part of ES2026. According to V8's write-up it shipped in Chromium 134, and MDN's compatibility data lists Node.js 24 for Symbol.asyncDispose, so use Node 24 or newer (see Node.js 26 LTS: what changed if you are still upgrading). Safari support has lagged, so for browser code check the compatibility tables on MDN before relying on it.
mkdir cleanup-demo && cd cleanup-demo
node --version # v24 or newer
npm init -y
# use ES modules
node -e "const p=require('./package.json');p.type='module';require('fs').writeFileSync('package.json',JSON.stringify(p,null,2))"
The model behind the JavaScript using keyword is simple: using x = value calls value[Symbol.dispose]() when the block ends, and await using x = value awaits value[Symbol.asyncDispose](). Both work like const, accept null or undefined, and run on normal exit, return, break and thrown errors.
Use plain using when releasing is synchronous (a timer, an in-memory lock). Use await using when releasing needs I/O, such as closing a file or removing a directory. Inside an async function you can mix both.
Step 2: Make a temp directory that deletes itself
Create temp-dir.js. The returned object carries a Symbol.asyncDispose method that removes the directory.
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
export async function createTempDir(prefix = 'job-') {
const path = await mkdtemp(join(tmpdir(), prefix));
return {
path,
async [Symbol.asyncDispose]() {
await rm(path, { recursive: true, force: true });
console.log('removed', path);
},
};
}
Nothing here is special to the language except the well-known symbol. Any object or class can opt in to await using in JavaScript the same way.
Step 3: Time a function with a synchronous using
Not every resource is async. A timer that logs on exit is a good small example. Create timer.js:
export function startTimer(label) {
const start = performance.now();
return {
[Symbol.dispose]() {
const ms = (performance.now() - start).toFixed(1);
console.log(`${label} took ${ms}ms`);
},
};
}
This replaces the classic const t = Date.now(); try { ... } finally { log(Date.now() - t) } pattern with one line at the top of any function.
Step 4: Put it together with a real FileHandle
Node's FileHandle is already async disposable (it is documented in the fs docs), so await using works on it directly. Create report.js:
import { open } from 'node:fs/promises';
import { join } from 'node:path';
import { createTempDir } from './temp-dir.js';
import { startTimer } from './timer.js';
export async function buildReport(rows) {
using _timer = startTimer('buildReport');
await using dir = await createTempDir();
await using fh = await open(join(dir.path, 'report.csv'), 'w');
await fh.write(rows.join('\n'));
const { size } = await fh.stat();
// Return plain data, not paths inside the temp dir:
// the directory is gone once this function exits.
return { size, rows: rows.length };
}
console.log(await buildReport(['id,name', '1,Ada', '2,Linus']));
Run node report.js. You should see the result object printed last, after the removed ... and buildReport took ...ms lines, because disposal happens before the caller receives the return value. There is no let, no try and no finally.
Step 5: Disposal order and early returns
Resources are disposed in reverse order of declaration, like a stack. In buildReport the file handle closes first, then the directory is removed, then the timer logs. That order is exactly what you want: you cannot delete a directory out from under an open handle on every platform.
Add an early return to prove the point:
if (rows.length === 0) return { size: 0, rows: 0 };
Place it after the await using lines and cleanup still runs. Place it before them and nothing was acquired, so nothing is disposed. That is a useful property: acquire late, and the block only cleans up what it actually opened.
Step 6: Errors during disposal and SuppressedError
What if cleanup itself fails while another error is already propagating? Instead of silently dropping the first error, the engine wraps both in a SuppressedError. Try it with a deliberately bad resource:
const bad = {
[Symbol.dispose]() { throw new Error('release failed'); },
};
try {
using _r = bad;
throw new Error('work failed');
} catch (e) {
console.log(e.name); // SuppressedError
console.log(e.error.message); // release failed (the disposal error)
console.log(e.suppressed.message);// work failed (the original error)
}
Note the naming: error is the newest error (from disposal) and suppressed is the earlier one. With several failing resources the errors chain, and because disposal runs in reverse order the original error ends up deepest. In your error handler, walk the chain so the root cause reaches your logs.
Step 7: TypeScript setup and gotchas
TypeScript supports the syntax since 5.2. Add the disposable libs so Symbol.dispose and DisposableStack type-check:
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "ESNext.Disposable"],
"module": "NodeNext"
}
}
Gotchas worth knowing before you use the JavaScript using keyword everywhere:
- No top-level use in classic scripts. It works at the top level of an ES module only.
- No reassignment. Declarations behave like
const. - The value must be disposable. Passing a plain object without the symbol method throws a
TypeError, so wrap third-party clients in a small adapter like Step 2. - Polyfill the symbols for older runtimes. Babel has a plugin for the syntax, and older targets need the symbols defined.
- Dispose is not a shutdown hook. It runs when a block exits, not on process signals. For SIGTERM handling see Node.js graceful shutdown.
When a resource must outlive the block that created it or you need to collect many cleanups conditionally, DisposableStack and AsyncDisposableStack offer use(), adopt(), defer() and move(). They are covered in the MDN guide; check their compatibility table for your target runtime.
Where to go next
You now have a job that cleans up after itself without a single finally. Good next candidates for the JavaScript using keyword in your own code are database connections leased from a pool, advisory locks, temp files in test suites (see the Node.js built-in test runner guide) and AbortController or timer cleanup. Make each one return an object with Symbol.dispose or Symbol.asyncDispose, and acquire it with using as late as possible. The V8 article and MDN guide are the best references for the details.





