{"id":13257,"library":"graphql-shield","title":"GraphQL Shield","description":"GraphQL Shield is a comprehensive library for implementing declarative permissions in GraphQL servers. It provides a robust and flexible rule-based system that acts as an additional layer of abstraction over your GraphQL schema. Currently stable at version 7.6.5, the package sees a moderate release cadence, primarily focusing on bug fixes and minor improvements, with significant feature additions occurring less frequently. Its key differentiators include its highly composable rule system (allowing `and`, `or`, `not` operations), deep integration with `graphql-middleware`, and strong TypeScript support, enabling developers to define complex access control logic in an organized and testable manner. It is essential for securing GraphQL APIs by preventing unauthorized data access or mutation.","status":"active","version":"7.6.5","language":"javascript","source_language":"en","source_url":"https://github.com/maticzav/graphql-shield","tags":["javascript","typescript"],"install":[{"cmd":"npm install graphql-shield","lang":"bash","label":"npm"},{"cmd":"yarn add graphql-shield","lang":"bash","label":"yarn"},{"cmd":"pnpm add graphql-shield","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core GraphQL library required for schema definition and execution.","package":"graphql","optional":false},{"reason":"Used to apply the shield rules as middleware to a GraphQL schema.","package":"graphql-middleware","optional":false}],"imports":[{"note":"The primary function to apply rules to your schema. Ensure named import for ESM.","wrong":"const shield = require('graphql-shield').shield;","symbol":"shield","correct":"import { shield } from 'graphql-shield';"},{"note":"Used to define custom asynchronous permission rules. Always a named import.","wrong":"import rule from 'graphql-shield/rule';","symbol":"rule","correct":"import { rule } from 'graphql-shield';"},{"note":"Utility rules for explicitly allowing or denying access. Best practice is to use named imports.","wrong":"const allow = require('graphql-shield').allow;","symbol":"allow","correct":"import { allow, deny } from 'graphql-shield';"},{"note":"Type definition for the rules object passed to `shield`. Import types separately.","symbol":"IRules","correct":"import type { IRules } from 'graphql-shield';"}],"quickstart":{"code":"import { GraphQLServer } from 'graphql-yoga';\nimport { shield, rule, allow, deny, and, or } from 'graphql-shield';\n\nconst isAuthenticated = rule({ cache: 'contextual' })(async (parent, args, ctx, info) => {\n  return ctx.user !== null;\n});\n\nconst isAdmin = rule({ cache: 'contextual' })(async (parent, args, ctx, info) => {\n  return ctx.user?.roles.includes('admin');\n});\n\nconst permissions = shield({\n  Query: {\n    '*': isAuthenticated, // All queries require authentication\n    user: or(isAuthenticated, isAdmin), // Example: user query specifically allows admin or authenticated\n    adminPanel: isAdmin,\n  },\n  Mutation: {\n    createUser: and(isAuthenticated, isAdmin),\n    updateUser: isAuthenticated,\n    deleteUser: deny,\n  },\n  // You can also define object type level rules\n  User: {\n    email: isAuthenticated,\n    roles: isAdmin\n  }\n});\n\nconst typeDefs = `\n  type User {\n    id: ID!\n    name: String!\n    email: String\n    roles: [String]\n  }\n\n  type Query {\n    hello: String!\n    user(id: ID!): User\n    adminPanel: String!\n  }\n\n  type Mutation {\n    createUser(name: String!, email: String!): User\n    updateUser(id: ID!, name: String): User\n    deleteUser(id: ID!): Boolean\n  }\n`;\n\nconst resolvers = {\n  Query: {\n    hello: () => 'Hello world!',\n    user: (parent: any, { id }: { id: string }, ctx: any) => ({ id, name: `User ${id}`, email: `user${id}@example.com`, roles: ['user'] }),\n    adminPanel: () => 'Welcome to the admin panel!'\n  },\n  Mutation: {\n    createUser: (parent: any, args: any) => ({ id: '1', ...args, roles: ['user'] }),\n    updateUser: (parent: any, args: any) => ({ id: args.id, name: args.name || 'Updated User', email: 'updated@example.com', roles: ['user'] }),\n    deleteUser: () => true,\n  }\n};\n\n// @ts-ignore - GraphQL Yoga handles middleware application\nconst server = new GraphQLServer({\n  typeDefs,\n  resolvers,\n  context: ({ request }) => ({ user: request.headers['authorization'] === 'Bearer admin' ? { id: 'admin', roles: ['admin'] } : { id: 'test', roles: ['user'] } })\n});\n\nserver.start(() => console.log('Server is running on http://localhost:4000'));","lang":"typescript","description":"Demonstrates defining custom rules for authentication and authorization, combining them with logical operators (`and`, `or`), and applying them to a GraphQL server using `graphql-yoga`."},"warnings":[{"fix":"For CommonJS environments, ensure your bundler (e.g., Webpack, Rollup) is configured to resolve `exports` maps or consider configuring Node.js to load your application as ESM by adding `\"type\": \"module\"` to your `package.json`.","message":"As of `graphql-shield@7.6.5`, the package prioritizes ESM builds. While CJS usage is still generally supported, users encountering build or import issues, especially in modern Node.js environments or bundled applications, should ensure their toolchain correctly handles ESM imports.","severity":"gotcha","affected_versions":">=7.6.5"},{"fix":"Check the `peerDependencies` in `graphql-shield`'s `package.json` and install a compatible version of `graphql-middleware`. For example, `npm install graphql-middleware@^6.0.0` or `yarn add graphql-middleware@^6.0.0`.","message":"The `graphql-middleware` peer dependency can have version compatibility issues. Ensure the installed version of `graphql-middleware` aligns with the ranges specified by `graphql-shield` to avoid runtime errors or unexpected behavior.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Upgrade to `graphql-shield@7.6.3` or newer to resolve issues with wildcard rule reusability. If upgrading is not possible, explicitly define rules for each field instead of relying solely on wildcard reusability.","message":"Previous versions (prior to `7.6.3`) had an issue where wildcard rules (`*`) were not properly reusable, leading to inconsistent permission application or unexpected behavior when trying to apply the same rule to multiple fields via wildcards.","severity":"gotcha","affected_versions":"<7.6.3"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Change your import statement to `import { shield } from 'graphql-shield';` and ensure your project or file is treated as an ES Module (e.g., by using `\"type\": \"module\"` in `package.json` or `.mjs` file extension).","cause":"Attempting to `require()` the `graphql-shield` package in a CommonJS module when the package is primarily designed for ESM or your environment enforces strict ESM resolution.","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module .../node_modules/graphql-shield/dist/esm/index.js from .../src/index.js not supported."},{"fix":"Ensure custom rules are defined with `rule()(() => ...)` and that `allow` or `deny` are imported directly and used as values, not called as functions without parameters (e.g., `allow` instead of `allow()`).","cause":"A rule defined using `rule()` was not correctly constructed or applied, or `allow`/`deny` were used incorrectly.","error":"Rule must be a function."},{"fix":"Ensure your GraphQL schema is a valid `GraphQLSchema` instance and is correctly passed as the first argument to `applyMiddleware` before `shield` is applied. For `graphql-yoga` or Apollo Server, ensure the `schema` or `typeDefs`/`resolvers` are properly configured before `shield` is used.","cause":"Occurs when `applyMiddleware` (from `graphql-middleware`) is not correctly integrated or the schema object passed to it is undefined.","error":"Cannot read properties of undefined (reading 'schema')"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null}