#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 61 of 62hard

What are Async Hooks in Node.js?

Tracking async resource lifecycle.

What You'll Learn

  • Async resource tracking
  • Hook callbacks
  • AsyncLocalStorage

Async Hooks

code.jsJavaScript
const async_hooks = require('async_hooks');

const hook = async_hooks.createHook({
  init(asyncId, type, triggerAsyncId) {
    console.log(`Init: ${type} (id: ${asyncId})`);
  },
  before(asyncId) {
    console.log(`Before: ${asyncId}`);
  },
  after(asyncId) {
    console.log(`After: ${asyncId}`);
  },
  destroy(asyncId) {
    console.log(`Destroy: ${asyncId}`);
  }
});

hook.enable();

setTimeout(() => {
  console.log('Timeout callback');
}, 100);

AsyncLocalStorage (Most Useful)

code.jsJavaScript
const { AsyncLocalStorage } = require('async_hooks');

const storage = new AsyncLocalStorage();

// Store request context
function middleware(req, res, next) {
  const context = {
    requestId: crypto.randomUUID(),
    userId: req.user?.id
  };

  storage.run(context, () => {
    next();
  });
}

// Access anywhere in async chain
function logMessage(message) {
  const context = storage.getStore();
  console.log(`[${context?.requestId}] ${message}`);
}

// Usage
app.use(middleware);

app.get('/api/data', async (req, res) => {
  logMessage('Processing request');  // Has access to requestId
  const data = await fetchData();
  logMessage('Data fetched');
  res.json(data);
});