Skip to content

cannot read stored value in asynclocalstorage when using finished #57844

Closed
@bjohansebas

Description

@bjohansebas

Version

v22.14.0 and probably previous versions

Platform

Linux bjohansebas 6.14.2-arch1-1 #1 SMP PREEMPT_DYNAMIC Thu, 10 Apr 2025 18:43:59 +0000 x86_64 GNU/Linux

Subsystem

stream, async_hooks

What steps will reproduce the bug?

While making a request and accessing AsyncLocalStorage, inside asyncLocalStorage the finished module is executed to access the value stored in the local storage.

const asyncHooks = require('async_hooks')
const http = require('http')
const finished = require('stream').finished
const assert = require('assert')

const asyncLocalStorage = new asyncHooks.AsyncLocalStorage()
const store = { foo: 'bar' }

var server = http.createServer(function (req, res) {
  asyncLocalStorage.run(store, function () {
    finished(res, function () {
      assert.strictEqual(asyncLocalStorage.getStore()?.foo, 'bar')
    })
  })
  setTimeout(res.end.bind(res), 0)

}).listen(0, function () {
  var port = this.address().port
  http.get('http://127.0.0.1:' + port, function onResponse(res) {
    res.resume()
    res.on('end', server.close.bind(server))
  })
})

How often does it reproduce? Is there a required condition?

Always

What is the expected behavior? Why is that the expected behavior?

It should be able to access the value stored in the local storage.

What do you see instead?

undefined

Image

Additional information

This is a test inside on-finished (see https://github.com/jshttp/on-finished/blob/f8b5f4097d28df79e466d1ffdf58ccb27d769156/test/test.js#L74)

This is important in order to use the finished function within the body-parser package. It's part of my experiment to stop using on-finished, but it will likely be merged if it passes all the tests, since the idea is to use the APIs provided by Node.js

expressjs/body-parser#598

Metadata

Metadata

Assignees

No one assigned

    Labels

    async_hooksIssues and PRs related to the async hooks subsystem.async_local_storageAsyncLocalStorageconfirmed-bugIssues with confirmed bugs.streamIssues and PRs related to the stream subsystem.

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions