What is graphql-shield and how does it work?
Answer
graphql-shield is a permission middleware library for GraphQL servers that lets you define authorization rules declaratively, separate from resolver logic. It uses a rule-based system where you define rules using rule() and apply them to types/fields using shield(). Rules can be composable with and(), or(), not(). Example: const isAuthenticated = rule()((parent, args, ctx) => ctx.user !== null); const isAdmin = rule()((parent, args, ctx) => ctx.user?.role === 'ADMIN'); const permissions = shield({ Query: { users: isAuthenticated, adminDashboard: isAdmin } });. Rules are cached per field by default (to avoid redundant checks). Shield integrates with Apollo Server as a schema transformation. It provides a clean separation of authorization concerns from business logic, making permission models easier to audit and maintain.
Previous
How do you implement authorization in GraphQL resolvers?
Next
How do you implement real-time subscriptions with GraphQL?
More GraphQL Questions
View all →- Intermediate How do you implement pagination in GraphQL?
- Intermediate What is the Relay specification in GraphQL?
- Intermediate How do you implement authorization in GraphQL resolvers?
- Intermediate How do you implement real-time subscriptions with GraphQL?
- Intermediate What is schema stitching in GraphQL?