{"id":12311,"library":"unload","title":"Universal Process Unload Handler","description":"The `unload` package provides a unified API for executing code reliably when a JavaScript process or environment is about to exit or unload. It abstracts away environment-specific mechanisms like `process.on('beforeExit')`, `process.on('SIGINT')`, `process.on('uncaughtException')` in Node.js, and `window.addEventListener('beforeunload')` or `window.addEventListener('unload')` in browsers, Electron, React Native, workers, and iframes. This ensures the registered exit functions are called only once, regardless of how the environment terminates. The current stable version is 2.4.1. It is particularly useful for library authors who need to clean up resources consistently across diverse JavaScript runtimes, ensuring robust shutdown procedures. It differs from simply using `process.on('exit')` by also handling abnormal terminations like `SIGINT` and `uncaughtException` in Node.js, and browser tab/window closures.","status":"active","version":"2.4.1","language":"javascript","source_language":"en","source_url":"https://github.com/pubkey/unload","tags":["javascript","unload","exit","onunload","SIGINT","uncaughtException","beforeExit","typescript"],"install":[{"cmd":"npm install unload","lang":"bash","label":"npm"},{"cmd":"yarn add unload","lang":"bash","label":"yarn"},{"cmd":"pnpm add unload","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"wrong":"const unload = require('unload');\nunload.add(function() {}); // CommonJS style, still works but ESM is preferred in modern codebases unless targeting Node.js only.","symbol":"add","correct":"import unload from 'unload';\nunload.add(() => { console.log('Exiting'); });"},{"note":"To clear all previously registered unload handlers. Commonly used in testing or when dynamically managing lifecycle.","symbol":"removeAll","correct":"import unload from 'unload';\nunload.removeAll();"},{"note":"Type import for the return value of `unload.add()`, which contains the `remove` method. Useful for TypeScript projects.","symbol":"UnloadReturnType","correct":"import unload, { UnloadReturnType } from 'unload';\nconst handler: UnloadReturnType = unload.add(() => {});"}],"quickstart":{"code":"import unload from 'unload';\n\nconst cleanupFunction = () => {\n  console.log('Performing cleanup before exit...');\n  // Simulate some asynchronous cleanup, though unload handlers should ideally be synchronous\n  // or complete very quickly to avoid delaying process termination.\n  try {\n    // For example, flushing logs or closing database connections\n    // In a real app, you might close a database connection here:\n    // myDatabase.close().then(() => console.log('DB closed')).catch(err => console.error('DB close error', err));\n    console.log('Cleanup complete!');\n  } catch (error) {\n    console.error('Error during cleanup:', error);\n  }\n};\n\nconst handler = unload.add(cleanupFunction);\n\nconsole.log('Unload handler registered. Try Ctrl+C or closing the browser tab/window.');\n\n// To demonstrate removal after some time (e.g., in an SPA where a component unmounts)\nsetTimeout(() => {\n  handler.remove();\n  console.log('Unload handler removed after 5 seconds.');\n  unload.add(() => console.log('A new handler added after removal, will run.'));\n}, 5000);\n\n// Simulate an uncaught exception in Node.js to see if handler runs\n// process.nextTick(() => { throw new Error('Simulated uncaught exception'); });\n","lang":"typescript","description":"Registers a cleanup function to run on process exit, demonstrates adding and removing handlers, and shows how it's used with TypeScript."},"warnings":[{"fix":"Ensure cleanup logic is as fast as possible. For critical async tasks, consider handling them earlier in the application lifecycle or logging potential failures for post-mortem analysis.","message":"Unload handlers, especially in browsers, should execute quickly and synchronously. Asynchronous operations may not complete before the environment terminates, potentially leading to data loss or incomplete cleanup. In Node.js, handlers are generally more robust but still prefer quick execution.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Design handlers to be idempotent and self-contained. Avoid inter-dependencies between different `unload.add()` calls.","message":"The `unload` package guarantees handlers run only once. However, if multiple libraries or parts of an application independently add handlers, the order of execution is not guaranteed, and handlers should not rely on the side effects of other handlers.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Migrate CommonJS `require('unload')` statements to ESM `import unload from 'unload';` for better tree-shaking and future compatibility in modern environments.","message":"While the README uses `var unload = require('unload');`, the package now primarily encourages ESM imports. Although CommonJS `require` still works, modern TypeScript and Node.js projects should use `import unload from 'unload';`.","severity":"breaking","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `unload` is imported as a default export: `import unload from 'unload';` for ESM, or `const unload = require('unload');` for CommonJS. Do not try `import { add } from 'unload';` as `add` is not a named export directly.","cause":"Attempting to call `add` on an `unload` object that was not correctly imported or initialized, often when mixing CJS and ESM, or if `unload` was destructured incorrectly.","error":"TypeError: unload.add is not a function"},{"fix":"Add `import unload from 'unload';` at the top of your ESM file or `const unload = require('unload');` for CommonJS files where `unload` is used.","cause":"The `unload` package has not been imported or required in the current scope.","error":"ReferenceError: unload is not defined"},{"fix":"Run `npm install unload` or `yarn add unload` to install the package. Verify that your build configuration (webpack, Rollup, etc.) correctly resolves `node_modules`.","cause":"The `unload` package is not installed or the module resolver cannot find it.","error":"Module not found: Can't resolve 'unload'"}],"ecosystem":"npm"}