How can we filter what entries are returned by a GraphQL query so that users cannot see entries authored by other people?

For example, Editors can access everything but Writers can only access their own entries.

1 Answer 1


You can do this using a custom module that adds an authorId condition to element queries, for graphql/api requests.

use Craft;
use craft\elements\db\EntryQuery;
use yii\base\Event;
use yii\web\ForbiddenHttpException;

// ...

// Is this a GraphQL request?
if (Craft::$app->request->getActionSegments() == ['graphql', 'api']) {
    Event::on(EntryQuery::class, EntryQuery::EVENT_BEFORE_PREPARE, function(Event $event) {
        // Get the current user
        $user = Craft::$app->user->identity;

        // If no one is logged in, return a 403 error
        if (!$user) {
            throw new ForbiddenHttpException();

        // Only Editors are allowed to see everything
        if (!$user->isInGroup('editors')) {
            /** @var EntryQuery $query */
            $query = $event->sender;
            $query->subQuery->andWhere(['authorId' => $user->id]);

Note: Since the results will start changing for the same element query depending on who is logged in, you’ll also need to disable the enableGraphQlCaching config setting.

  • Make sure you are using the correct config name for your Craft version: enableGraphQlCaching before Craft CMS 3.7 and enableGraphqlCaching after Craft CMS 3.7 Commented Aug 23, 2021 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.