Control data and query access in a GraphQL API

The graphQL API provides a simple way to authorize incoming requests. Each GraphQLQuery instance has a authorize method, that takes in a function that must return true or false to indicate if the current request should be authorized or not.

The authorization function receives the current graphQL context. This contains all the information about the current request, including a manager instance for easy database access.


You may call the authorize method on a GraphQLQuery instance to add a new authorization function. You may call this method as many times as you need. All of the authorization functions will be run, and if any of them return false, the request will throw an Unauthorized error.

import { tensei, graphQlQuery } from '@tensei/core'

export default tensei()
        graphQlQuery('Get Purchases')
            .authorize(async ({ user }) => user?.hasPermission('Get Purchases'))
            .handle(async (parent, args, ctx, info) => ctx.user.purchases)

If you are using the auth plugin, the context passed to the authorize function will contain the currently authenticated user.

Authorizing existing queries

You may wish to add custom authorization functions on queries automatically generated by Tensei. To do this, first you need to get the query, and call the authorize function with your own authorization function. A good place to do this is in the export default tensei().register() function.

import { tensei } from '@tensei/core'

export default tensei()
    .register(({ getQuery }) => {
            ?.authorize(({ user, body }) => body.comment.user !==