{"id":13727245,"url":"https://github.com/teamplanes/graphql-rate-limit","last_synced_at":"2026-01-19T20:08:50.922Z","repository":{"id":33971218,"uuid":"164230160","full_name":"teamplanes/graphql-rate-limit","owner":"teamplanes","description":"Add Rate Limiting To Your GraphQL Resolvers 💂‍♀️","archived":false,"fork":false,"pushed_at":"2023-10-17T02:55:59.000Z","size":1037,"stargazers_count":411,"open_issues_count":24,"forks_count":29,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-27T19:48:03.316Z","etag":null,"topics":["graphql","javascript","nodejs","security","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","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/teamplanes.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"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}},"created_at":"2019-01-05T16:06:33.000Z","updated_at":"2025-04-23T13:56:21.000Z","dependencies_parsed_at":"2024-01-07T21:16:37.504Z","dependency_job_id":null,"html_url":"https://github.com/teamplanes/graphql-rate-limit","commit_stats":{"total_commits":116,"total_committers":13,"mean_commits":8.923076923076923,"dds":0.3793103448275862,"last_synced_commit":"368c77f1a89c0f048142ee3953901ad8e464199e"},"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teamplanes%2Fgraphql-rate-limit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teamplanes%2Fgraphql-rate-limit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teamplanes%2Fgraphql-rate-limit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teamplanes%2Fgraphql-rate-limit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/teamplanes","download_url":"https://codeload.github.com/teamplanes/graphql-rate-limit/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252965261,"owners_count":21832853,"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":["graphql","javascript","nodejs","security","typescript"],"created_at":"2024-08-03T01:03:45.778Z","updated_at":"2026-01-19T20:08:50.916Z","avatar_url":"https://github.com/teamplanes.png","language":"TypeScript","readme":"\n\u003ch1 align=\"center\"\u003e💂‍♀️ GraphQL Rate Limit 💂‍♂️\u003c/h1\u003e\n\n\u003cp align=\"center\"\u003e\nA GraphQL Rate Limiter to add basic but granular rate limiting to your Queries or Mutations.\n\u003c/p\u003e\n\n---\n\n## Features\n\n- 💂‍♀️ Add rate limits to queries or mutations\n- 🤝 Works with any Node.js GraphQL setup (@directive, graphql-shield rule and a base rate limiter function for every other use case)\n- 🔑 Add filters to rate limits based on the query or mutation args\n- ❌ Custom error messaging\n- ⏰ Configure using a simple `max` per `window` arguments\n- 💼 Custom stores, use Redis, Postgres, Mongo... it defaults to in-memory\n- 💪 Written in TypeScript\n\n\n## Install\n\n```sh\nyarn add graphql-rate-limit\n```\n\n## Examples\n\n#### Option 1: Using the @directive\n\n```ts\nimport { createRateLimitDirective } from 'graphql-rate-limit';\n\n// Step 1: get rate limit directive instance\nconst rateLimitDirective = createRateLimitDirective({ identifyContext: (ctx) =\u003e ctx.id });\n\nconst schema = makeExecutableSchema({\n  schemaDirectives: {\n    rateLimit: rateLimitDirective\n  },\n  resolvers: {\n    Query: {\n      getItems: () =\u003e [{ id: '1' }]\n    }\n  },\n  typeDefs: gql`\n    directive @rateLimit(\n      max: Int,\n      window: String,\n      message: String,\n      identityArgs: [String],\n      arrayLengthField: String\n    ) on FIELD_DEFINITION\n\n    type Query {\n      # Step 2: Apply the rate limit instance to the field with config\n      getItems: [Item] @rateLimit(window: \"1s\", max: 5, message: \"You are doing that too often.\")\n    }\n  `\n});\n```\n\n#### Option 2: Using the graphql-shield\n\n```ts\nimport { createRateLimitRule } from 'graphql-rate-limit';\n\n// Step 1: get rate limit shield instance rule\nconst rateLimitRule = createRateLimitRule({ identifyContext: (ctx) =\u003e ctx.id });\n\nconst permissions = shield({\n  Query: {\n    // Step 2: Apply the rate limit rule instance to the field with config\n    getItems: rateLimitRule({ window: \"1s\", max: 5 })\n  }\n});\n\nconst schema = applyMiddleware(\n  makeExecutableSchema({\n    typeDefs: gql`\n      type Query {\n        getItems: [Item]\n      }\n    `,\n    resolvers: {\n      Query: {\n        getItems: () =\u003e [{ id: '1' }]\n      }\n    }\n  }),\n  permissions\n)\n```\n\n#### Option 3: Using the base rate limiter function\n\n```ts\nimport { getGraphQLRateLimiter } from 'graphql-rate-limit';\n\n// Step 1: get rate limit directive instance\nconst rateLimiter = getGraphQLRateLimiter({ identifyContext: (ctx) =\u003e ctx.id });\n\nconst schema = makeExecutableSchema({\n  typeDefs: `\n    type Query {\n      getItems: [Item]\n    }\n  `,\n  resolvers: {\n    Query: {\n      getItems: async (parent, args, context, info) =\u003e {\n        // Step 2: Apply the rate limit logic instance to the field with config\n        const errorMessage = await rateLimiter(\n          { parent, args, context, info },\n          { max: 5, window: '10s' }\n        );\n        if (errorMessage) throw new Error(errorMessage);\n        return [{ id: '1' }]\n      }\n    }\n  }\n})\n```\n\n## Configuration\n\nYou'll notice that each usage example has two steps, step 1 we get an instace of a rate limiter and step 2 we apply the rate limit to one or more fields. When creating the initial instance we pass 'Instance Config' (e.g. `identifyContext` or a `store` instance), this instance will likely be the only instance you'd create for your entire GraphQL backend and can be applied to multiple fields.\n\nOnce you have your rate limiting instance you'll apply it to all the fields that require rate limiting, at this point you'll pass field level rate limiting config (e.g. `window` and `max`).\n\nAnd so... we have the same 'Instance Config' and 'Field Config' options which ever way you use this library.\n\n### Instance Config\n\n#### `identifyContext`\n\nA required key and used to identify the user/client. The most likely cases are either using the context's request.ip, or the user ID on the context. A function that accepts the context and returns a string that is used to identify the user.\n\n```js\nidentifyContext: (ctx) =\u003e ctx.user.id\n```\n\n#### `store`\n\nAn optional key as it defaults to an InMemoryStore. See the implementation of InMemoryStore if you'd like to implement your own with your own database.\n\n\n```js\nstore: new MyCustomStore()\n```\n\n#### `formatError`\n\nGenerate a custom error message. Note that the `message` passed in to the field config will be used if its set.\n\n```js\nformatError: ({ fieldName }) =\u003e `Woah there, you are doing way too much ${fieldName}`\n```\n\n\n#### `createError`\n\nGenerate a custom error. By default, a [`RateLimitError`](https://github.com/teamplanes/graphql-rate-limit/blob/master/src/lib/rate-limit-error.ts) instance is created when a request is blocked. To return an instance of a different error class, you can return your own error using this field.\n\n```js\ncreateError: (message: string) =\u003e new ApolloError(message, '429');\n```\n\n#### `enableBatchRequestCache`\n\nThis enables a per-request synchronous cache to properly rate limit batch queries. Defaults to `false` to preserve backwards compatibility. \n\n```js\nenableBatchRequestCache: false | true\n```\n\n### Field Config\n\n#### `window`\n\nSpecify a time interval window that the `max` number of requests can access the field. We use Zeit's `ms` to parse the `window` arg, [docs here](https://github.com/zeit/ms).\n\n#### `max`\n\nDefine the max number of calls to the given field per `window`.\n\n#### `identityArgs`\n\nIf you wanted to limit the requests to a field per id, per user, use `identityArgs` to define how the request should be identified. For example you'd provide just `[\"id\"]` if you wanted to rate limit the access to a field by `id`. We use Lodash's `get` to access nested identity args, [docs here](https://lodash.com/docs/4.17.11#get).\n\n#### `message`\n\nA custom message per field. Note you can also use `formatError` to customise the default error message if you don't want to define a single message per rate limited field.\n\n#### `arrayLengthField`\n\nLimit calls to the field, using the length of the array as the number of calls to the field.\n\n\n## Redis Store Usage\n\nIt is recommended to use a persistent store rather than the default InMemoryStore. GraphQLRateLimit currently supports Redis as an alternative. You'll need to install Redis in your project first.\n\n```js\nimport { createRateLimitDirective, RedisStore } from 'graphql-rate-limit';\n\nconst GraphQLRateLimit = createRateLimitDirective({\n  identifyContext: ctx =\u003e ctx.user.id,\n  /**\n   * Import the class from graphql-rate-limit and pass in an instance of redis client to the constructor\n   */\n  store: new RedisStore(redis.createClient())\n});\n```\n","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fteamplanes%2Fgraphql-rate-limit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fteamplanes%2Fgraphql-rate-limit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fteamplanes%2Fgraphql-rate-limit/lists"}