Building Custom GraphQL Resolvers in Magento 2 for Headless Storefronts
How to extend the Magento 2 GraphQL schema with your own queries and mutations — schema files, resolver classes, authorization, caching, and avoiding N+1 queries.
Headless Magento lives and dies by its GraphQL layer. Core covers catalog, cart and checkout well, but every real project needs custom data: store locators, add-on services, B2B pricing, ERP fields. Here's how I build custom resolvers that are fast, secure, and upgrade-safe.
Module structure
A minimal GraphQL module looks like this:
app/code/Acme/StoreLocator/
├── etc/
│ ├── module.xml
│ └── schema.graphqls
├── Model/
│ └── Resolver/
│ ├── StoreLocations.php
│ └── Identity/StoreLocationIdentity.php
└── registration.phpMake sure module.xml declares a sequence dependency on Magento_GraphQl so your schema merges after core.
Step 1 — Define the schema
Magento merges every module's etc/schema.graphqls into one schema. Declare your types and attach a resolver class with the @resolver directive:
type Query {
storeLocations(city: String @doc(description: "Filter by city")): [StoreLocation]
@resolver(class: "Acme\\StoreLocator\\Model\\Resolver\\StoreLocations")
@doc(description: "Returns physical store locations")
@cache(cacheIdentity: "Acme\\StoreLocator\\Model\\Resolver\\Identity\\StoreLocationIdentity")
}
type StoreLocation @doc(description: "A physical store") {
id: Int!
name: String!
city: String
latitude: Float
longitude: Float
opening_hours: String
}Step 2 — Write the resolver
A resolver implements ResolverInterface and returns plain arrays that match the schema:
<?php
declare(strict_types=1);
namespace Acme\StoreLocator\Model\Resolver;
use Acme\StoreLocator\Api\LocationRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
class StoreLocations implements ResolverInterface
{
public function __construct(
private readonly LocationRepositoryInterface $locationRepository,
private readonly SearchCriteriaBuilder $searchCriteriaBuilder
) {
}
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
$storeId = (int) $context->getExtensionAttributes()->getStore()->getId();
$this->searchCriteriaBuilder
->addFilter('store_id', [$storeId, 0], 'in')
->addFilter('is_active', 1);
if (!empty($args['city'])) {
$this->searchCriteriaBuilder->addFilter('city', $args['city']);
}
$items = $this->locationRepository
->getList($this->searchCriteriaBuilder->create())
->getItems();
return array_map(static fn ($location) => [
'id' => (int) $location->getId(),
'name' => $location->getName(),
'city' => $location->getCity(),
'latitude' => (float) $location->getLatitude(),
'longitude' => (float) $location->getLongitude(),
'opening_hours' => $location->getOpeningHours(),
], array_values($items));
}
}Keep resolvers thin
Resolvers should translate GraphQL ↔ service contracts. Put business logic in repositories and services so REST, cron jobs and admin can reuse it.
Step 3 — Secure mutations
Queries are often public, but mutations usually aren't. Check the customer context and throw the GraphQL-specific exceptions so clients get proper error categories:
<?php
use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
// inside resolve()
if (false === $context->getExtensionAttributes()->getIsCustomer()) {
throw new GraphQlAuthorizationException(__('The current customer isn\'t authorized.'));
}
if (empty($args['input']['note'])) {
throw new GraphQlInputException(__('"note" is required.'));
}
$customerId = (int) $context->getUserId();Never trust a customer_id passed in arguments — always derive it from the context.
Step 4 — Make it cacheable
GraphQL GET queries can be cached by Varnish/Fastly just like pages. The @cache(cacheIdentity: ...) directive tells Magento which cache tags a response carries, so saving a location in admin invalidates exactly the right entries:
<?php
declare(strict_types=1);
namespace Acme\StoreLocator\Model\Resolver\Identity;
use Magento\Framework\GraphQl\Query\Resolver\IdentityInterface;
class StoreLocationIdentity implements IdentityInterface
{
private const CACHE_TAG = 'acme_store_location';
public function getIdentities(array $resolvedData): array
{
$ids = [self::CACHE_TAG];
foreach ($resolvedData as $location) {
$ids[] = self::CACHE_TAG . '_' . $location['id'];
}
return $ids;
}
}Your model's getIdentities() must return the same tags so admin saves purge them.
Step 5 — Avoid N+1 queries
When a field is resolved for each item in a list (e.g. an extra attribute on every product in a category), a naïve resolver fires one SQL query per item. Use BatchResolverInterface (or a collector/deferred pattern) to load everything in one query:
- Collect all parent IDs first.
- Load the related data in a single collection call.
- Map results back to each parent.
On a 48-product category page that's the difference between 48 queries and 1.
Testing tips
- Use Postman or Altair collections checked into the repo so the frontend team can explore your schema.
- Write API functional tests extending
GraphQlAbstractfor critical queries. - Watch the
X-Magento-Cache-Debugheader to confirmHITs on cacheable queries.
Building a headless storefront and need a solid GraphQL layer? See my headless commerce services, the Accuride Europe project where I built a GraphQL layer for a ReactJS frontend, or let's talk.
