Scott and Wes explore the world of AsyncLocalStorage and AsyncContext API, discussing their potential in sharing context among the call stack, middleware applications, and frameworks like Next.js and Cloudflare Workers. They also provide examples of usage and caution against potential footguns.
Read more
AI Summary
AI Chapters
Episode notes
auto_awesome
Podcast summary created with Snipd AI
Quick takeaways
AsyncLocalStorage allows you to define a store inside a function, making it easier to share data between function calls without manual passing of references or values.
Many frameworks are not yet using AsyncLocalStorage widely due to its reliance on a Node.js API, but a proposal for an async context API in JavaScript could offer similar functionality across all runtimes.
Deep dives
Async Local Storage in JavaScript
Async local storage is a new API in JavaScript that allows you to define a store inside a function, which can be accessed anywhere down the call stack. It provides a way to share data between multiple function calls without passing references or values manually. It is particularly useful for logging and tracing request IDs, user sessions, and user preferences. It can also simplify console logging by storing data like show numbers and accessing it in different functions. However, using async local storage may present some challenges, such as testing and potential memory leaks if not handled properly.
Async Local Storage in Node.js
Async local storage was introduced in Node.js version 13 and has gained momentum due to its usefulness. While some frameworks, like Next.js and Cloudflare Workers, have implemented it to access cookies and headers, many frameworks are not using it widely due to its reliance on a Node.js API. However, there is a proposal in tc39 to add an async context API to JavaScript, which would offer similar functionality across all JavaScript runtimes.
Benefits and Considerations
Using async local storage eliminates the need to pass data between functions manually, which simplifies code and makes it cleaner. It can be especially beneficial for scenarios where data needs to be accessed at different levels of the call stack. However, it's important to consider potential foot guns, such as difficulties in testing and the possibility of memory leaks. Additionally, async local storage may have use cases beyond server-side, such as handling events in the browser.