BitlystBitlyst
PostsSeriesTopicsAbout

Bitlyst

Short, diagram-first posts on JavaScript, React & Next.js. Follow via RSS or the newsletter.

© 2026 Mohsen Fallahnejad

PostsSeriesTopicsLinksAboutSync devicesRSSllms.txtGitHubX
Posts/nodejs
AI-generated illustration. Same badge in every room, without anyone handing it over.
Intermediate4 min read

AsyncLocalStorage: A Name Badge for Every Request

AsyncLocalStorage in Node.js gives each request its own data that follows it through every await. Learn how it works and how Next.js cookies() uses it.

Mohsen Fallahnejad

Mohsen Fallahnejad

Dec 1, 2026Discuss

Have you ever wondered how cookies() in Next.js knows which user's cookies to give you? You never pass it the request. You call it from deep inside some component, and somehow it knows.

Your server is handling hundreds of requests at the same time. So how does it keep them apart? The answer is AsyncLocalStorage, a small Node.js tool with a big job.

The whole idea in one picture#

Think of a big conference. At the door, every guest gets a name badge. Wherever they go after that, any room, any talk, any coffee line, anyone can glance at the badge and know who they are. Nobody has to walk next to them shouting their name.

AsyncLocalStorage pins a name badge on a request at the start. Any code that runs for that request, even after an await or a timer, can read the badge.

That's the whole idea. The rest is how Node keeps the badges from getting mixed up.

The problem it solves#

Say you want every log line to include the request ID. Without a badge, you have to pass it by hand into every function:

ts
async function handle(req) {
  const requestId = req.id;
  await loadUser(requestId);   // pass it
  await loadOrders(requestId); // pass it again
}
// ...and loadUser passes it on, and so on, forever

That's like carrying someone's name on a sign behind them all day. It works, but every function has to take the sign and hand it on, even if it doesn't care.

AI-generated illustration. Passing it by hand works, until the tenth function that has to carry it.AI-generated illustration. Passing it by hand works, until the tenth function that has to carry it.

How it works#

You create one storage, put the badge on at the start of a request with run(), and read it anywhere with getStore():

ts
import { AsyncLocalStorage } from "node:async_hooks";

const als = new AsyncLocalStorage();
const log = (msg) => console.log(`[${als.getStore()?.requestId}] ${msg}`);

async function loadUser() {
  await new Promise((r) => setTimeout(r, 10));
  log("loaded user"); // no requestId passed in!
}

for (const id of ["a1", "b2"]) {
  als.run({ requestId: id }, async () => {
    log("start");
    await loadUser();
    log("done");
  });
}

Output:

txt
[a1] start
[b2] start
[a1] loaded user
[a1] done
[b2] loaded user
[b2] done

Both requests run at the same time, but each one keeps its own badge, even across the await and the timer. Outside run(), getStore() gives you undefined. There's no badge if you never came through the door.

How does Node pull this off? Every time your code schedules something for later (a promise, a setTimeout, a network call), Node copies the current badge onto it. When that work runs later, the badge is put back on. That's why it survives every hop.

In practice#

You probably use it already without knowing:

  • Next.js runs each request inside AsyncLocalStorage. That's how cookies(), headers() and after() know which request they belong to.
  • Logging and tracing tools (like OpenTelemetry) use it to stamp every log and span with the right request.
  • Your own code can use it for request IDs, the current user, or a per-request database transaction.

One honest catch: since Node copies the badge onto every timer and promise, a long timer keeps the whole request in memory until it fires. That's exactly what caused a 5 GB leak in the timer that kept every request. Keep what you put in the store small, and be careful with long timers during a request.

Say it in an interview#

"AsyncLocalStorage is Node's way to keep per-request data without passing it through every function. You call run(store, fn) at the start of a request, and anything inside it, even after await or a setTimeout, can read the same data with getStore(). Node does this by copying the current context onto every async task it schedules. Next.js uses it for cookies() and headers(). The catch is that pending timers keep that context alive, so long timers can hold requests in memory."

Cheat sheet#

QuestionShort answer
What is it?Per-request data that follows async code
Put the badge onals.run(store, fn)
Read the badgeals.getStore()
Outside run()?undefined
Who uses it?Next.js cookies() / headers(), logging, tracing
The catchPending timers and promises keep the store alive

Advanced · optional

Going deeper#

Everything above is enough to explain this in an interview. This part is for the curious: full numbers, edge cases and what's still unproven.

Why not a global variable?#

A global works when there's one request at a time. Node handles many at once on a single thread: request A hits an await, request B runs, then A continues. A global would hold B's data by then. AsyncLocalStorage gives each chain of async work its own value.

run() vs enterWith()#

run(store, fn) puts the badge on only for fn and everything it schedules, then takes it off. enterWith(store) puts it on for the rest of the current synchronous code and has no clear end, so it's easy to leak into places you didn't expect. Prefer run().

Beyond Node#

Deno, Bun and Cloudflare Workers support AsyncLocalStorage too. There's also a TC39 proposal, AsyncContext, to add the same idea to JavaScript itself, including browsers.

Further reading#

  • Node.js docs: AsyncLocalStorage
Filed under#nodejs#nextjs#async#javascript#interview

Was this worth your time?

One tap tells me what to write more of.

Mohsen Fallahnejad

Written by

Mohsen Fallahnejad

Frontend engineer explaining JavaScript, React & Next.js internals in posts you can finish over coffee. More about me

X ↗GitHub ↗LinkedIn ↗
← OlderNext.js Memory Leak: The Timer That Kept Every Request

Start the discussion

Questions, corrections, a better approach? I read and reply to every comment.

Read next

Next.js Memory Leak: The Timer That Kept Every Request

A Next.js memory leak where one setTimeout per SSR render kept finished requests in memory. How it was spotted, measured with heap snapshots, and fixed.

Nov 30, 20266 min read

async vs defer: Why Script Order Breaks Your Page

async vs defer on a script tag: both download without blocking, but async runs the moment it arrives and defer waits for the HTML, in order. Learn which to pick.

Nov 27, 20264 min read

forEach and async/await: Why Your Loop Doesn't Wait

forEach with async/await doesn't wait. It starts every callback and returns undefined, so your code moves on early and errors skip your try/catch. Use for...of or Promise.all.

Nov 23, 20264 min read

Get new posts in your inbox

One email when a new post is out: short, diagram-first explanations of JavaScript, React and Next.js. No spam, unsubscribe any time.

4 min left
Discuss👍 React
👍