Every program that opens something has to close it. Files, database connections, locks, timers, event listeners, temporary directories: they all need cleaning up, and they need cleaning up even when something throws. In JavaScript that has always meant try...finally, and try...finally gets awkward fast. Forget it once and you leak a file handle. Open three resources and you end up with three levels of nesting.
Explicit resource management adds two declarations, using and await using, that tie cleanup to a block. When the block ends, for any reason, the resource is disposed. This article is for JavaScript and TypeScript developers who write code that acquires things and needs to release them, which in practice means most back-end code and a fair amount of front-end and test code. We will start with the problem, build up the API, and finish with where it runs today and when to avoid it.
The problem with try and finally
#Here is a function that writes to a file, using Node's promise-based file API.
_12import { open } from "node:fs/promises";_12_12async function writeReport(path, lines) {_12 const file = await open(path, "w");_12 try {_12 for (const line of lines) {_12 await file.write(line + "\n");_12 }_12 } finally {_12 await file.close();_12 }_12}
That is fine for one resource. Add a lock and a second file and it looks like this:
_18async function copyWithLock(lock, from, to) {_18 const release = await lock.acquire();_18 try {_18 const source = await open(from, "r");_18 try {_18 const target = await open(to, "w");_18 try {_18 await source.readFile().then((data) => target.write(data));_18 } finally {_18 await target.close();_18 }_18 } finally {_18 await source.close();_18 }_18 } finally {_18 release();_18 }_18}
The cleanup is far away from the code that needs it, the nesting grows with every resource, and the order of the finally blocks has to be kept right by hand.
The disposable protocol
#Explicit resource management starts with two well-known symbols.
Symbol.disposenames a method that cleans up synchronously.Symbol.asyncDisposenames a method that cleans up and returns a promise.
Any object with one of these methods is a disposable. You can add them to your own classes.
_11class TempFlag {_11 constructor(target, name) {_11 this.target = target;_11 this.name = name;_11 target.classList.add(name);_11 }_11_11 [Symbol.dispose]() {_11 this.target.classList.remove(this.name);_11 }_11}
On its own that is just a method with an unusual name. The new declarations are what call it.
using
#A using declaration looks like const, and like const it cannot be reassigned. The difference is that when the enclosing block exits, the value's Symbol.dispose method is called.
_10function highlightWhileSaving(form) {_10 using flag = new TempFlag(form, "is-saving");_10_10 validate(form);_10 save(form);_10} // flag[Symbol.dispose]() runs here, even if validate or save throws
The rules are short:
- Disposal happens when the block exits, whether by reaching the end, by
return, bybreakorcontinue, or by an exception. - If you declare several resources, they are disposed in reverse order, so the last one acquired is the first one released.
- The value can be
nullorundefined, in which case nothing is disposed. That makes optional resources easy. - Any other value without a
Symbol.disposemethod throws aTypeErrorat the declaration, not later. - The binding must be a simple name. Destructuring, as in
using { a, b } = thing, is not allowed.
You can also use it in a for...of loop, so each item is disposed at the end of its iteration.
_10for (using connection of openConnections(hosts)) {_10 connection.ping();_10}
await using
#Most real cleanup is asynchronous: closing a file, ending a database session, flushing a log. await using handles that. At the end of the block it calls Symbol.asyncDispose and awaits the result before carrying on. If the object only has Symbol.dispose, that is used instead.
await using is only allowed where await is, so inside async functions and at the top level of modules.
In Node.js, the FileHandle objects returned by open from node:fs/promises already implement Symbol.asyncDispose, so the first example becomes:
_10import { open } from "node:fs/promises";_10_10async function writeReport(path, lines) {_10 await using file = await open(path, "w");_10_10 for (const line of lines) {_10 await file.write(line + "\n");_10 }_10}
And the three-resource version flattens out completely:
_10async function copyWithLock(lock, from, to) {_10 using held = await lock.acquire(); // returns an object with Symbol.dispose_10 await using source = await open(from, "r");_10 await using target = await open(to, "w");_10_10 await target.write(await source.readFile());_10}_10// disposed in order: target, source, held
Each resource is acquired and its cleanup is registered on the same line. There is no way to forget the close.
Writing your own disposables
#The pattern works best when the function that acquires a resource returns a disposable. Here is a small database transaction helper.
_27async function beginTransaction(pool) {_27 const client = await pool.connect();_27 await client.query("BEGIN");_27 let committed = false;_27_27 return {_27 client,_27 async commit() {_27 await client.query("COMMIT");_27 committed = true;_27 },_27 async [Symbol.asyncDispose]() {_27 if (!committed) {_27 await client.query("ROLLBACK");_27 }_27 client.release();_27 },_27 };_27}_27_27async function transferFunds(pool, from, to, amount) {_27 await using tx = await beginTransaction(pool);_27_27 await tx.client.query("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [amount, from]);_27 await tx.client.query("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [amount, to]);_27 await tx.commit();_27}
If either query throws, the transaction rolls back and the connection goes back to the pool. If both succeed, commit runs and disposal just releases the connection.
The same shape is useful in tests. A helper that temporarily changes something can restore it automatically.
_16function withEnv(name, value) {_16 const previous = process.env[name];_16 process.env[name] = value;_16_16 return {_16 [Symbol.dispose]() {_16 if (previous === undefined) delete process.env[name];_16 else process.env[name] = previous;_16 },_16 };_16}_16_16test("uses the staging API", () => {_16 using _env = withEnv("API_URL", "https://staging.example.com");_16 expect(getApiUrl()).toBe("https://staging.example.com");_16});
When cleanup throws: SuppressedError
#What happens if the block throws and then the dispose method throws too? With try...finally, the error from finally silently replaces the original one, which makes bugs very hard to trace.
Explicit resource management keeps both. It throws a SuppressedError, whose error property is the error from disposal and whose suppressed property is the error it replaced.
_12try {_12 using res = {_12 [Symbol.dispose]() {_12 throw new Error("cleanup failed");_12 },_12 };_12 throw new Error("work failed");_12} catch (err) {_12 console.log(err instanceof SuppressedError); // true_12 console.log(err.error.message); // "cleanup failed"_12 console.log(err.suppressed.message); // "work failed"_12}
If only the dispose method throws, you get that error directly. If only the block throws, you get the original error, as you would expect.
DisposableStack and AsyncDisposableStack
#Sometimes you do not know how many resources you will acquire, or you are working with an API that has a close method but no Symbol.dispose. DisposableStack and AsyncDisposableStack collect cleanup work and run it in reverse order when the stack itself is disposed.
use(value)adds a disposable and returns it.adopt(value, onDispose)adds any value along with a function to clean it up.defer(fn)adds a plain cleanup callback.move()transfers everything to a new stack, leaving the original empty.
_18function watchElements(elements, onResize) {_18 using stack = new DisposableStack();_18_18 for (const el of elements) {_18 const observer = stack.adopt(new ResizeObserver(onResize), (o) => o.disconnect());_18 observer.observe(el);_18 }_18_18 const controller = stack.adopt(new AbortController(), (c) => c.abort());_18 window.addEventListener("resize", onResize, { signal: controller.signal });_18_18 // Everything set up without throwing, so hand it to the caller_18 return stack.move();_18}_18_18const watching = watchElements(document.querySelectorAll(".panel"), update);_18// later_18watching.dispose();
The move call is the useful trick here. If anything throws while setting up, the using declaration disposes the partly built stack. If setup succeeds, ownership moves to the caller, and the now empty original stack disposes nothing.
Using it in TypeScript
#TypeScript has supported using and await using since version 5.2. Two settings matter:
- Add
esnext(or the narroweresnext.disposable) tolibso theDisposable,AsyncDisposable,DisposableStackandSuppressedErrortypes are available. - If your
targetis older than the version that includes the feature, TypeScript rewritesusinginto equivalenttry...finallycode with helpers. That code still needsSymbol.disposeandSymbol.asyncDisposeto exist at runtime, so older environments need a polyfill.
_10{_10 "compilerOptions": {_10 "target": "es2022",_10 "lib": ["es2022", "esnext.disposable", "dom"]_10 }_10}
Your own disposables can be typed with the built-in interfaces.
_10class Lock implements Disposable {_10 constructor(private release: () => void) {}_10_10 [Symbol.dispose](): void {_10 this.release();_10 }_10}
Babel also has a plugin that transforms the syntax, if your build uses it.
Browser and runtime support
#As of late 2026, native support is uneven, so check your targets before shipping the syntax untransformed.
- Chrome and Edge support it from version 134, released in March 2025.
- Firefox supports it from version 141, released in July 2025.
- Safari does not support it yet, on macOS or iOS. That is why the feature is not yet Baseline.
- Node.js supports it from Node 24, which ships a V8 version that includes it, so it works on Node 24 and later. Node 22, which is still in maintenance LTS, does not support it.
FileHandleinnode:fs/promisesimplementsSymbol.asyncDispose.
In practice, that means:
- Server code on Node 24 or later can use it directly.
- Browser code that must work in Safari needs to be compiled by TypeScript or Babel, plus a small polyfill for the symbols and, if you use them,
DisposableStackandSuppressedError.
When not to use it
#- When the lifetime is not a block. A WebSocket that stays open for the whole session, or a cache that lives as long as the app, does not fit a lexical scope. Use
DisposableStackwithmove, or ordinary lifecycle code such as a React effect cleanup. - When you need to handle cleanup errors differently. If a failing
closeshould be logged and ignored rather than thrown, a hand-writtentry...finallywith its owncatchis clearer. - In browser code shipped without a build step. Until Safari supports it, untransformed
usingis a syntax error there, and a syntax error stops the whole script from running. - To replace simple, single cleanups that are already clear. A short
try...finallythat closes one thing is not a problem worth solving.
Wrapping up
#usingcallsSymbol.disposeandawait usingcallsSymbol.asyncDisposewhen the enclosing block exits, however it exits.- Multiple resources are disposed in reverse order, and
nullorundefinedare skipped. - If both the block and the cleanup throw, you get a
SuppressedErrorthat keeps both errors. DisposableStackandAsyncDisposableStackhandle dynamic sets of resources and APIs without dispose methods, andmovehands ownership to the caller.- It runs natively in Chromium, Firefox and Node 24 or later. Safari still needs a transform and polyfill.
Test yourself
Testing yourself is one of the best ways to make what you read stick. Turn over each card and answer the 5 questions to see how much you remember.
quick question
Was this article helpful?
by Danny