Nodejs async hooks with next callback not working and crashing nodemon

183 views Asked by At

Nodejs async hooks with run function having next not getting called and it crashing the nodemon

Here is my async local storage (asyncContext.ts)

import { AsyncLocalStorage } from 'async_hooks';

const asyncContext = new AsyncLocalStorage<Map<string, string>>();
export default asyncContext;

Request handler middleware

import { Response, NextFunction } from 'express';
import { customAlphabet } from 'nanoid/async';
import { Request } from '../../interfaces/Request';
import asyncLocalStorage from '../asyncContext';

export const requestIdHandler = async (req: Request, res: Response, next: NextFunction) => {
  req.id = await customAlphabet('1234567890abcdefghijklmnopqrstuvwxyz', 20)();
  const store = new Map<string, string>();
  asyncLocalStorage.run(store, () => {
    store.set('requestId', req.id);
    res.setHeader('X-Request-Id', req.id);
    next();
  });
};

As soon as the application run and trigger any api getting following error

[nodemon] app crashed - waiting for file changes before starting...

if i will remove the asyncLocalStorage.run function application will working properly.

UPDATE - if runs without nodemon it's working properly Any help or reference will be very helpful, thanks

0

There are 0 answers