{"id":43868163,"url":"https://github.com/zhujun24/http-request-context","last_synced_at":"2026-02-06T13:29:00.958Z","repository":{"id":57268300,"uuid":"203984249","full_name":"zhujun24/http-request-context","owner":"zhujun24","description":"Store context in http request's lifecycle.","archived":false,"fork":false,"pushed_at":"2020-04-23T08:32:26.000Z","size":39,"stargazers_count":7,"open_issues_count":3,"forks_count":4,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-09-28T18:38:05.904Z","etag":null,"topics":["context","http","http-context","middleware","nodejs","request","request-context","scoped"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zhujun24.png","metadata":{"files":{"readme":"README.md","changelog":"History.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-08-23T11:18:27.000Z","updated_at":"2025-09-26T17:50:12.000Z","dependencies_parsed_at":"2022-09-02T02:01:57.372Z","dependency_job_id":null,"html_url":"https://github.com/zhujun24/http-request-context","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/zhujun24/http-request-context","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zhujun24%2Fhttp-request-context","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zhujun24%2Fhttp-request-context/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zhujun24%2Fhttp-request-context/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zhujun24%2Fhttp-request-context/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zhujun24","download_url":"https://codeload.github.com/zhujun24/http-request-context/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zhujun24%2Fhttp-request-context/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29162156,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-06T12:44:37.655Z","status":"ssl_error","status_checked_at":"2026-02-06T12:44:13.991Z","response_time":59,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["context","http","http-context","middleware","nodejs","request","request-context","scoped"],"created_at":"2026-02-06T13:29:00.317Z","updated_at":"2026-02-06T13:29:00.939Z","avatar_url":"https://github.com/zhujun24.png","language":"JavaScript","readme":"# HTTP Request Context\n\n[![npm package](https://nodei.co/npm/http-request-context.png?downloads=true\u0026downloadRank=true\u0026stars=true)](https://www.npmjs.com/package/http-request-context)\n\n[![Build Status](https://travis-ci.org/zhujun24/http-request-context.svg)](https://travis-ci.org/zhujun24/http-request-context)\n[![Coverage Status](https://coveralls.io/repos/github/zhujun24/http-request-context/badge.svg?branch=master)](https://coveralls.io/github/zhujun24/http-request-context?branch=master)\n[![Known Vulnerabilities](https://snyk.io//test/github/zhujun24/http-request-context/badge.svg?targetFile=package.json)](https://snyk.io//test/github/zhujun24/http-request-context?targetFile=package.json)\n[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fzhujun24%2Fhttp-request-context.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fzhujun24%2Fhttp-request-context?ref=badge_shield)\n[![npm package](https://img.shields.io/npm/v/http-request-context.svg)](https://www.npmjs.com/package/http-request-context)\n\n[![NPM downloads](https://img.shields.io/npm/dm/http-request-context.svg)](https://www.npmjs.com/package/http-request-context)\n[![Dependency Status](https://david-dm.org/zhujun24/http-request-context.svg)](https://www.npmjs.com/package/http-request-context)\n[![Dependency Status](https://david-dm.org/zhujun24/http-request-context/dev-status.svg)](https://www.npmjs.com/package/http-request-context)\n[![Standard - JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://www.npmjs.com/package/http-request-context)\n\nSet and Get request-scoped context anywhere.\n\n## Requirement\n\n### Nodejs version \u003e= 8.2.0\n\nThis module uses the newer [async_hooks](https://nodejs.org/api/async_hooks.html#async_hooks_async_hooks) API which is considered `Experimental` by Nodejs.\n\n## Options\n\n| Option | Description | Type | Default |\n|:------------|:------------|:------------|:------------|\n| interval | remove expired callstack interval(s) | Number | 10\n| expire | callstack expire time(s)| Number | 150\n| removeAfterFinish | remove callstack after [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) [finish](https://nodejs.org/api/http.html#http_event_finish) | Boolean | false\n| removeAfterClose | remove callstack after [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) [close](https://nodejs.org/api/http.html#http_event_close_1) | Boolean | false\n\n#### options.interval\n\nRemove expired callstack interval, used like `setInterval(removeExpiredCallstack, interval)`.\n\n#### options.expire\n\nCallstack expire time, must be longer than full lifecycle of a request.\n\n#### options.removeAfterFinish\n\nIt will actively remove the relevant callstack after [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) [finish](https://nodejs.org/api/http.html#http_event_finish).\n\nIf set to `true`, you can get the context synchronously in the finish event, but not asynchronous. The benefit is that it can improve the performance of this middleware.\n\n#### options.removeAfterClose\n\nThis is very similar to `options.removeAfterFinish`, the difference is that after the close event.\n\nPlease Note! if set to `true`, in some cases, the close event may be caused by the client terminating the request, after the close event, we may still use the context after the incomplete asynchronous operation is completed, this will result in loss of context.\n\n## Init Middleware\n\n**This module is recommend as a \"top-level\" middleware for ensure all context can be tracked**\n\n- `httpRequestContext.middleware(options)` Init Express middleware.\n- `httpRequestContext.koaMiddleware(options)` Init Koa middleware.\n\n## Set Context\n\n- `httpRequestContext.set(key, value)` Set context anywhere.\n- `httpRequestContext.set({ key: value })` This is also OK.\n\n## Get Context\n\n- `httpRequestContext.get(key)` Get the `[key]` attribute of the context.\n- `httpRequestContext.get()` Gets an object containing all context properties.\n\n## How to Use\n\nsee [example](https://github.com/zhujun24/http-request-context/tree/master/example) here.\n\n### Install\n\n```npm\nnpm install http-request-context --save\n```\n\n### Express\n\n#### Init\n\n```js\nimport httpRequestContext from 'http-request-context'\n\napp.use(httpRequestContext.middleware())\n```\n\n#### Set Context\n\n```js\nimport httpRequestContext from 'http-request-context'\n\n// set context by key-value\napp.use((req, res, next) =\u003e {\n  setTimeout(() =\u003e {\n    httpRequestContext.set('foo', 'bar')\n    next()\n  }, 100)\n})\n```\n\n#### Get Context\n\n```js\nimport httpRequestContext from 'http-request-context'\n\nhttpRequestContext.get('foo') // 'bar'\n```\n\n### Koa\n\n#### Init\n\n```js\nimport httpRequestContext from 'http-request-context'\n\napp.use(httpRequestContext.koaMiddleware())\n```\n\n#### Set Context\n\n```js\nimport httpRequestContext from 'http-request-context'\n\n// set context by key-value\napp.use(async (ctx, next) =\u003e {\n  await new Promise(resolve =\u003e {\n    setTimeout(() =\u003e {\n      httpRequestContext.set('user', 'user')\n      resolve()\n    }, 300)\n  })\n  await next()\n})\n```\n\n##### Get Context\n\n```js\nimport httpRequestContext from 'http-request-context'\n\nhttpRequestContext.get('foo') // 'bar'\n```\n\n## Lost Context Tips\n\n#### http.ServerResponse close event\n\nSometimes, when client terminate request by close window or reload page, it will cause http.ServerResponse emit 'close' event, this event is trigger by root, so it break away from current request scope, in this case, we can add `res`(express) or `ctx.res`(koa) parameter to get context function to ensure context can be tracked, as follows:\n\n```js\n// Express\nres.on('close', () =\u003e {\n  console.log('close', httpRequestContext.get('foo', res))\n})\n\n// Koa\nctx.res.on('close', () =\u003e {\n  console.log('close', httpRequestContext.get('foo', ctx.res))\n})\n```\n\n#### MySQL\n\nIf you init mysql connect before http server start, you may get context undefined in mysql query callback scope.\n\n[googleapis/cloud-trace-nodejs #946](https://github.com/googleapis/cloud-trace-nodejs/issues/946)\n\n[nodejs/node #22360](https://github.com/nodejs/node/issues/22360)\n\n```js\nmysqlConnection.query('SELECT * FROM table', (error, results, fields) =\u003e {\n  httpRequestContext.get('foo') // undefined\n})\n```\n\nYou can use util.promisify to avoid it.\n\n```js\nutil.promisify(mysqlConnection.query).bind(mysqlConnection)('SELECT * FROM table')\n  .then((results, fields) =\u003e {\n    httpRequestContext.get('foo') // 'bar'\n  })\n  .catch(error =\u003e {})\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzhujun24%2Fhttp-request-context","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzhujun24%2Fhttp-request-context","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzhujun24%2Fhttp-request-context/lists"}