⬡ GraphQL Intermediate

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.