|
| 1 | +--- |
| 2 | +title: Directly import `waitUntil` in Workers for easily spawning background tasks |
| 3 | +description: You can now import `waitUntil` from `cloudflare:workers` to extend execution of background tasks without requiring the request context |
| 4 | +products: |
| 5 | + - workers |
| 6 | +date: 2025-08-08 |
| 7 | +--- |
| 8 | + |
| 9 | +You can now import [`waitUntil`](/workers/runtime-apis/context/#waituntil) from `cloudflare:workers` to extend your Worker's execution beyond the request lifecycle from anywhere in your code. |
| 10 | + |
| 11 | +Previously, `waitUntil` could only be accessed through the [execution context](/workers/runtime-apis/context/) (`ctx`) parameter passed to your Worker's handler functions. This meant that if you needed to schedule background tasks from deeply nested functions or utility modules, you had to pass the `ctx` object through multiple function calls to access `waitUntil`. |
| 12 | + |
| 13 | +Now, you can import `waitUntil` directly and use it anywhere in your Worker without needing to pass `ctx` as a parameter: |
| 14 | + |
| 15 | +```js |
| 16 | +import { waitUntil } from "cloudflare:workers"; |
| 17 | + |
| 18 | +export function trackAnalytics(eventData) { |
| 19 | + const analyticsPromise = fetch("https://analytics.example.com/track", { |
| 20 | + method: "POST", |
| 21 | + body: JSON.stringify(eventData), |
| 22 | + }); |
| 23 | + |
| 24 | + // Extend execution to ensure analytics tracking completes |
| 25 | + waitUntil(analyticsPromise); |
| 26 | +} |
| 27 | +``` |
| 28 | + |
| 29 | +This is particularly useful when you want to: |
| 30 | + |
| 31 | +- Schedule background tasks from utility functions or modules |
| 32 | +- Extend execution for analytics, logging, or cleanup operations |
| 33 | +- Avoid passing the execution context through multiple layers of function calls |
| 34 | + |
| 35 | +```js |
| 36 | +import { waitUntil } from "cloudflare:workers"; |
| 37 | + |
| 38 | +export default { |
| 39 | + async fetch(request, env, ctx) { |
| 40 | + // Background task that should complete even after response is sent |
| 41 | + cleanupTempData(env.KV_NAMESPACE); |
| 42 | + return new Response("Hello, World!"); |
| 43 | + } |
| 44 | +}; |
| 45 | + |
| 46 | +function cleanupTempData(kvNamespace) { |
| 47 | + // This function can now use waitUntil without needing ctx |
| 48 | + const deletePromise = kvNamespace.delete("temp-key"); |
| 49 | + waitUntil(deletePromise); |
| 50 | +} |
| 51 | +``` |
| 52 | + |
| 53 | +:::note |
| 54 | +The imported `waitUntil` function works the same way as [`ctx.waitUntil()`](/workers/runtime-apis/context/#waituntil). It extends your Worker's execution to wait for the provided promise to settle, but does not block the response from being sent to the client. |
| 55 | +::: |
| 56 | + |
| 57 | +For more information, see the [`waitUntil` documentation](/workers/runtime-apis/context/#waituntil). |
0 commit comments