onShutdown() & close()
onShutdown()
Section titled “onShutdown()”Signature
Section titled “Signature”app.onShutdown(fn)Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
fn | Function | Cleanup function (sync or async). |
Returns: app (for chaining).
Example
Section titled “Example”app.onShutdown(async () => { await db.disconnect(); console.log("Database closed");});
// Chainingapp .onShutdown(() => db.disconnect()) .onShutdown(() => cache.close()) .start(3000);Hooks run sequentially in registration order. If one throws, remaining hooks still execute.
close()
Section titled “close()”Signature
Section titled “Signature”// Promise APIawait app.close();
// Callback APIapp.close(callback);Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
callback | Function | Optional. Called with (err) when shutdown completes. |
Returns:
- Without callback:
Promise<void> - With callback:
app
Behavior
Section titled “Behavior”- Stops the server from accepting new connections
- Drains existing requests (up to configured timeout)
- Runs all registered
onShutdownhooks - Resolves / calls callback
Safe to call multiple times — second call resolves immediately (idempotent).
Example
Section titled “Example”// Programmatic shutdown in testsafterAll(async () => { await app.close();});
// Callback styleapp.close((err) => { if (err) console.error("Shutdown error:", err); process.exit(err ? 1 : 0);});