Plugins
Field Authorize
Field Authorize
The field Authorize Plugin plugin provides a new property on the field config called authorize
.
1import { makeSchema, fieldAuthorizePlugin } from 'nexus'23const schema = makeSchema({4 // ... types, etc,5 plugins: [6 // ... other plugins7 fieldAuthorizePlugin(),8 ],9})
It allows us to define field-level authorization to a query:
1t.field('postById', {2 type: Post,3 args: { id: idArg() },4 authorize: (root, args, ctx) => ctx.auth.canViewPost(args.id),5 resolve(root, args, ctx) {6 return ctx.post.byId(args.id)7 },8})
authorize
is a function that provides authorization for an individual field. Returning true
or Promise<true>
means the field can be accessed. Returning false
or Promise<false>
will respond with a "Not Authorized" error for the field. Returning or throwing an error will also prevent the resolver from executing.