Control data and query access in a REST API

The graphQL API provides a simple way to authorize incoming requests. Each Route 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 request. 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 Route 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, route } from '@tensei/core'

        route('Get Purchases')
            .authorize(({ customer }) => !!customer)
            .authorize(async ({ customer }) => customer?.hasPermission('Get Purchases'))
            .handle(async (parent, args, ctx, info) => ctx.customer.purchases)

In the above example, two authorization checks will be performed before executing the request handler.

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

Authorizing existing routes

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

import { tensei } from '@tensei/core'

    .register(({ getRoute }) => {
            ?.authorize(({ user, body }) => body?.comment?.user !==