{"id":13411339,"url":"https://github.com/BackendStack21/http-cache-middleware","last_synced_at":"2025-03-14T17:30:37.867Z","repository":{"id":37008082,"uuid":"189103424","full_name":"BackendStack21/http-cache-middleware","owner":"BackendStack21","description":"HTTP Cache Middleware","archived":false,"fork":false,"pushed_at":"2023-09-20T06:30:35.000Z","size":165,"stargazers_count":29,"open_issues_count":2,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-05-20T03:19:38.068Z","etag":null,"topics":["cache","http","middleware","rest"],"latest_commit_sha":null,"homepage":null,"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/BackendStack21.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"custom":"https://www.paypal.me/kyberneees"}},"created_at":"2019-05-28T21:06:27.000Z","updated_at":"2024-06-18T18:24:54.669Z","dependencies_parsed_at":"2024-06-18T18:36:48.119Z","dependency_job_id":null,"html_url":"https://github.com/BackendStack21/http-cache-middleware","commit_stats":null,"previous_names":["jkyberneees/http-cache-middleware"],"tags_count":22,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BackendStack21%2Fhttp-cache-middleware","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BackendStack21%2Fhttp-cache-middleware/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BackendStack21%2Fhttp-cache-middleware/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BackendStack21%2Fhttp-cache-middleware/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/BackendStack21","download_url":"https://codeload.github.com/BackendStack21/http-cache-middleware/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243324468,"owners_count":20273110,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["cache","http","middleware","rest"],"created_at":"2024-07-30T20:01:13.010Z","updated_at":"2025-03-14T17:30:37.485Z","avatar_url":"https://github.com/BackendStack21.png","language":"JavaScript","readme":"# http-cache-middleware\n[![NPM version](https://badgen.net/npm/v/http-cache-middleware)](https://www.npmjs.com/package/http-cache-middleware)\n[![NPM Total Downloads](https://badgen.net/npm/dt/http-cache-middleware)](https://www.npmjs.com/package/http-cache-middleware)\n[![License](https://badgen.net/npm/license/http-cache-middleware)](https://www.npmjs.com/package/http-cache-middleware)\n[![TypeScript support](https://badgen.net/npm/types/http-cache-middleware)](https://www.npmjs.com/package/http-cache-middleware)\n[![Github stars](https://badgen.net/github/stars/jkyberneees/http-cache-middleware?icon=github)](https://github.com/jkyberneees/http-cache-middleware)\n\n\u003cimg src=\"logo.svg\" width=\"400\"\u003e  \n\nHigh performance connect-like HTTP cache middleware for Node.js. So your latency can decrease to single digit milliseconds 🚀 \n\n\u003e Uses `cache-manager` as caching layer, so multiple\nstorage engines are supported, i.e: Memory, Redis, ... https://www.npmjs.com/package/cache-manager\n\n## Install\n```js \nnpm i http-cache-middleware\n```\n\n## Usage\n```js\nconst middleware = require('http-cache-middleware')()\nconst service = require('restana')()\nservice.use(middleware)\n\nservice.get('/cache-on-get', (req, res) =\u003e {\n  setTimeout(() =\u003e {\n    // keep response in cache for 1 minute if not expired before\n    res.setHeader('x-cache-timeout', '1 minute')\n    res.send('this supposed to be a cacheable response')\n  }, 50)\n})\n\nservice.delete('/cache', (req, res) =\u003e {\n  // ... the logic here changes the cache state\n\n  // expire the cache keys using pattern\n  res.setHeader('x-cache-expire', '*/cache-on-get')\n  res.end()\n})\n\nservice.start(3000)\n```\n## Redis cache\n```js\n// redis setup\nconst CacheManager = require('cache-manager')\nconst redisStore = require('cache-manager-ioredis')\nconst redisCache = CacheManager.caching({\n  store: redisStore,\n  db: 0,\n  host: 'localhost',\n  port: 6379,\n  ttl: 30\n})\n\n// middleware instance\nconst middleware = require('http-cache-middleware')({\n  stores: [redisCache]\n})\n```\n\n## Why cache? \n\u003e Because caching is the last mile for low latency distributed systems!\n\nEnabling proper caching strategies will drastically reduce the latency of your system, as it reduces network round-trips, database calls and CPU processing.  \nFor our services, we are talking here about improvements in response times from `X ms` to `~2ms`, as an example.\n\n### Enabling cache for service endpoints\nEnabling a response to be cached just requires the \n`x-cache-timeout` header to be set:\n```js\nres.setHeader('x-cache-timeout', '1 hour')\n```\n\u003e Here we use the [`ms`](`https://www.npmjs.com/package/ms`) package to convert timeout to seconds. Please note that `millisecond` unit is not supported!  \n\nExample on service using `restana`:\n```js\nservice.get('/numbers', (req, res) =\u003e {\n  res.setHeader('x-cache-timeout', '1 hour')\n\n  res.send([\n    1, 2, 3\n  ])\n})\n```\n\n### Caching on the browser side (304 status codes)\n\u003e From version `1.2.x` you can also use the HTTP compatible `Cache-Control` header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control\nWhen using the Cache-Control header, you can omit the custom `x-cache-timeout` header as the timeout can be passed using the `max-age` directive. \n\n#### Direct usage: \n```js \nres.setHeader('cache-control', 'private, no-cache, max-age=300')\nres.setHeader('etag', 'cvbonrw6g00')\n\nres.end('5 minutes cacheable content here....')\n```\n\n#### Indirect usage:\nWhen using:\n```js\nres.setHeader('x-cache-timeout', '5 minutes')\n```\nThe middleware will now transparently generate default `Cache-Control` and `ETag` headers as described below:\n```js \nres.setHeader('cache-control', 'private, no-cache, max-age=300')\nres.setHeader('etag', 'ao8onrw6gbt') // random ETag value \n```\nThis will enable browser clients to keep a copy of the cache on their side, but still being forced to validate \nthe cache state on the server before using the cached response, therefore supporting gateway based cache invalidation. \n\n\u003e NOTE: In order to fetch the generated `Cache-Control` and `ETag` headers, there have to be at least one cache hit.\n\n### Invalidating caches \nServices can easily expire cache entries on demand, i.e: when the data state changes. Here we use the `x-cache-expire` header to indicate the cache entries to expire using a matching pattern:\n```js\nres.setHeader('x-cache-expire', '*/numbers')\n```\n\u003e Here we use the [`matcher`](`https://www.npmjs.com/package/matcher`) package for matching patterns evaluation.\n\nExample on service using `restana`:\n```js\nservice.patch('/numbers', (req, res) =\u003e {\n  // ...\n\n  res.setHeader('x-cache-expire', '*/numbers')\n  res.send(200)\n})\n```\n\n#### Invalidating multiple patterns\nSometimes is required to expire cache entries using multiple patterns, that is also possible using the `,` separator:\n```js\nres.setHeader('x-cache-expire', '*/pattern1,*/pattern2')\n```\n\n#### Direclty invalidating caches from stores\n```js\nconst stores = [redisCache]\nconst middleware = require('http-cache-middleware')({\n  stores\n})\n\nconst { deleteKeys } = require('http-cache-middleware/utils')\ndeleteKeys(stores, '*/pattern1,*/pattern2')\n```\n\n### Custom cache keys\nCache keys are generated using: `req.method + req.url`, however, for indexing/segmenting requirements it makes sense to allow cache keys extensions.  \n\nTo accomplish this, we simply recommend using middlewares to extend the keys before caching checks happen:\n```js\nservice.use((req, res, next) =\u003e {\n  req.cacheAppendKey = (req) =\u003e req.user.id // here cache key will be: req.method + req.url + req.user.id  \n  return next()\n})\n```\n\u003e In this example we also distinguish cache entries by `user.id`, commonly used for authorization reasons.\n\nIn case full control of the `cache-key` value is preferred, just populate the `req.cacheKey` property with a `string` value. In this case, the req.method + req.url prefix is discarded:\n```js\nservice.use((req, res, next) =\u003e {\n  req.cacheKey = 'CUSTOM-CACHE-KEY'\n  return next()\n})\n```\n\n### Disable cache for custom endpoints\nYou can also disable cache checks for certain requests programmatically:\n```js\nservice.use((req, res, next) =\u003e {\n  req.cacheDisabled = true\n  return next()\n})\n```\n\n## Want to contribute?\nThis is your repo ;)  \n\n\u003e Note: We aim to be 100% code coverage, please consider it on your pull requests.\n\n## Related projects\n- fast-gateway (https://www.npmjs.com/package/fast-gateway)\n\n## Sponsors\n- (INACTIVE) Kindly sponsored by [ShareNow](https://www.share-now.com/), a company that promotes innovation!  \n\n## Support / Donate 💚\nYou can support the maintenance of this project: \n- Paypal: https://www.paypal.me/kyberneees\n- [TRON](https://www.binance.com/en/buy-TRON) Wallet: `TJ5Bbf9v4kpptnRsePXYDvnYcYrS5Tyxus`","funding_links":["https://www.paypal.me/kyberneees"],"categories":["Web Development"],"sub_categories":["Javascript"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBackendStack21%2Fhttp-cache-middleware","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FBackendStack21%2Fhttp-cache-middleware","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBackendStack21%2Fhttp-cache-middleware/lists"}