Gathering detailed insights and metrics for graphql-rate-limit
Gathering detailed insights and metrics for graphql-rate-limit
Gathering detailed insights and metrics for graphql-rate-limit
Gathering detailed insights and metrics for graphql-rate-limit
@envelop/rate-limiter
This plugins uses [`graphql-rate-limit`](https://github.com/teamplanes/graphql-rate-limit#readme) in order to limit the rate of calling queries and mutations.
graphql-rate-limit-directive
Fixed window rate-limiting directive for GraphQL. Use to limit repeated requests to queries and mutations.
express-rate-limit
Basic IP rate-limiting middleware for Express. Use to limit repeated requests to public APIs and/or endpoints such as password reset.
rate-limit-redis
A Redis store for the `express-rate-limit` middleware
npm install graphql-rate-limit
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
410 Stars
141 Commits
28 Forks
4 Watching
22 Branches
11 Contributors
Updated on 02 Aug 2024
Minified
Minified + Gzipped
TypeScript (87.76%)
JavaScript (12.24%)
Cumulative downloads
Total Downloads
Last day
-13.6%
5,415
Compared to previous day
Last week
8.7%
29,337
Compared to previous week
Last month
9.4%
114,067
Compared to previous month
Last year
-16%
1,083,283
Compared to previous year
4
1
23
A GraphQL Rate Limiter to add basic but granular rate limiting to your Queries or Mutations.
max
per window
arguments1yarn add graphql-rate-limit
1import { createRateLimitDirective } from 'graphql-rate-limit'; 2 3// Step 1: get rate limit directive instance 4const rateLimitDirective = createRateLimitDirective({ identifyContext: (ctx) => ctx.id }); 5 6const schema = makeExecutableSchema({ 7 schemaDirectives: { 8 rateLimit: rateLimitDirective 9 }, 10 resolvers: { 11 Query: { 12 getItems: () => [{ id: '1' }] 13 } 14 }, 15 typeDefs: gql` 16 directive @rateLimit( 17 max: Int, 18 window: String, 19 message: String, 20 identityArgs: [String], 21 arrayLengthField: String 22 ) on FIELD_DEFINITION 23 24 type Query { 25 # Step 2: Apply the rate limit instance to the field with config 26 getItems: [Item] @rateLimit(window: "1s", max: 5, message: "You are doing that too often.") 27 } 28 ` 29});
1import { createRateLimitRule } from 'graphql-rate-limit'; 2 3// Step 1: get rate limit shield instance rule 4const rateLimitRule = createRateLimitRule({ identifyContext: (ctx) => ctx.id }); 5 6const permissions = shield({ 7 Query: { 8 // Step 2: Apply the rate limit rule instance to the field with config 9 getItems: rateLimitRule({ window: "1s", max: 5 }) 10 } 11}); 12 13const schema = applyMiddleware( 14 makeExecutableSchema({ 15 typeDefs: gql` 16 type Query { 17 getItems: [Item] 18 } 19 `, 20 resolvers: { 21 Query: { 22 getItems: () => [{ id: '1' }] 23 } 24 } 25 }), 26 permissions 27)
1import { getGraphQLRateLimiter } from 'graphql-rate-limit';
2
3// Step 1: get rate limit directive instance
4const rateLimiter = getGraphQLRateLimiter({ identifyContext: (ctx) => ctx.id });
5
6const schema = makeExecutableSchema({
7 typeDefs: `
8 type Query {
9 getItems: [Item]
10 }
11 `,
12 resolvers: {
13 Query: {
14 getItems: async (parent, args, context, info) => {
15 // Step 2: Apply the rate limit logic instance to the field with config
16 const errorMessage = await rateLimiter(
17 { parent, args, context, info },
18 { max: 5, window: '10s' }
19 );
20 if (errorMessage) throw new Error(errorMessage);
21 return [{ id: '1' }]
22 }
23 }
24 }
25})
You'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.
Once 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
).
And so... we have the same 'Instance Config' and 'Field Config' options which ever way you use this library.
identifyContext
A 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.
1identifyContext: (ctx) => ctx.user.id
store
An 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.
1store: new MyCustomStore()
formatError
Generate a custom error message. Note that the message
passed in to the field config will be used if its set.
1formatError: ({ fieldName }) => `Woah there, you are doing way too much ${fieldName}`
createError
Generate a custom error. By default, a RateLimitError
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.
1createError: (message: string) => new ApolloError(message, '429');
enableBatchRequestCache
This enables a per-request synchronous cache to properly rate limit batch queries. Defaults to false
to preserve backwards compatibility.
1enableBatchRequestCache: false | true
window
Specify 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.
max
Define the max number of calls to the given field per window
.
identityArgs
If 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.
message
A 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.
arrayLengthField
Limit calls to the field, using the length of the array as the number of calls to the field.
It 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.
1import { createRateLimitDirective, RedisStore } from 'graphql-rate-limit';
2
3const GraphQLRateLimit = createRateLimitDirective({
4 identifyContext: ctx => ctx.user.id,
5 /**
6 * Import the class from graphql-rate-limit and pass in an instance of redis client to the constructor
7 */
8 store: new RedisStore(redis.createClient())
9});
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
Found 5/19 approved changesets -- score normalized to 2
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
39 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More