Registry / auth-security / graphql-shield

graphql-shield

JSON →
library7.6.5jsnpmunverified

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.

npm install graphql-shield
INSTALL
IMPORT
SIG · GRAPHQL-SHIELD
G
graphql-shield
auth-securityjavascriptv7.6.5
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

shield
import { shield } from 'graphql-shield';
const shield = require('graphql-shield').shield;
The primary function to apply rules to your schema. Ensure named import for ESM.
rule
import { rule } from 'graphql-shield';
import rule from 'graphql-shield/rule';
Used to define custom asynchronous permission rules. Always a named import.
allow
import { allow, deny } from 'graphql-shield';
const allow = require('graphql-shield').allow;
Utility rules for explicitly allowing or denying access. Best practice is to use named imports.
IRules
import type { IRules } from 'graphql-shield';
Type definition for the rules object passed to `shield`. Import types separately.

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`.

import { GraphQLServer } from 'graphql-yoga'; import { shield, rule, allow, deny, and, or } from 'graphql-shield'; const isAuthenticated = rule({ cache: 'contextual' })(async (parent, args, ctx, info) => { return ctx.user !== null; }); const isAdmin = rule({ cache: 'contextual' })(async (parent, args, ctx, info) => { return ctx.user?.roles.includes('admin'); }); const permissions = shield({ Query: { '*': isAuthenticated, // All queries require authentication user: or(isAuthenticated, isAdmin), // Example: user query specifically allows admin or authenticated adminPanel: isAdmin, }, Mutation: { createUser: and(isAuthenticated, isAdmin), updateUser: isAuthenticated, deleteUser: deny, }, // You can also define object type level rules User: { email: isAuthenticated, roles: isAdmin } }); const typeDefs = ` type User { id: ID! name: String! email: String roles: [String] } type Query { hello: String! user(id: ID!): User adminPanel: String! } type Mutation { createUser(name: String!, email: String!): User updateUser(id: ID!, name: String): User deleteUser(id: ID!): Boolean } `; const resolvers = { Query: { hello: () => 'Hello world!', user: (parent: any, { id }: { id: string }, ctx: any) => ({ id, name: `User ${id}`, email: `user${id}@example.com`, roles: ['user'] }), adminPanel: () => 'Welcome to the admin panel!' }, Mutation: { createUser: (parent: any, args: any) => ({ id: '1', ...args, roles: ['user'] }), updateUser: (parent: any, args: any) => ({ id: args.id, name: args.name || 'Updated User', email: 'updated@example.com', roles: ['user'] }), deleteUser: () => true, } }; // @ts-ignore - GraphQL Yoga handles middleware application const server = new GraphQLServer({ typeDefs, resolvers, context: ({ request }) => ({ user: request.headers['authorization'] === 'Bearer admin' ? { id: 'admin', roles: ['admin'] } : { id: 'test', roles: ['user'] } }) }); server.start(() => console.log('Server is running on http://localhost:4000'));
Debug
Known issues
gotchaAs 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.
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`.
affects: >=7.6.5
gotchaThe `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.
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`.
affects: >=2.0.0
gotchaPrevious 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.
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.
affects: <7.6.3
Errors
Common errors & fixes
Error [ERR_REQUIRE_ESM]: require() of ES Module .../node_modules/graphql-shield/dist/esm/index.js from .../src/index.js not supported.
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.
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).
Rule must be a function.
A rule defined using `rule()` was not correctly constructed or applied, or `allow`/`deny` were used incorrectly.
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()`).
Cannot read properties of undefined (reading 'schema')
Occurs when `applyMiddleware` (from `graphql-middleware`) is not correctly integrated or the schema object passed to it is undefined.
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.
Upgrade
Version history
7.6.5latest on npm
Audit
Dependencies
graphqlrequiredCore GraphQL library required for schema definition and execution.
graphql-middlewarerequiredUsed to apply the shield rules as middleware to a GraphQL schema.
Agent activity
17 hits · last 30 days
node
16
OpenAI (training)
1
Resources
graphql-shield — npm install graphql-shield · libregistry