Symfony Serializer groups: stop leaking fields
The classic way a private field leaks: someone writes json_encode($user) in an API controller, a passwordHash property gets added to the class six months later, and nobody notices that the endpoint now returns it. I stopped hand-building response arrays and started letting the Symfony Serializer decide what leaves the building, using serialization groups. The component also works fine outside a full Symfony app, which makes it handy in Drupal custom code.
Mark what is public with attributes
Groups live on the properties themselves. The attributes are Groups and SerializedName from the Serializer documentation. A readonly DTO with promoted constructor properties works well because the attributes sit right next to the type:
<?php
declare(strict_types=1);
namespace App\Dto;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Serializer\Attribute\SerializedName;
enum AccountStatus: string
{
case Active = 'active';
case Suspended = 'suspended';
}
final class AccountView
{
public function __construct(
#[Groups(['public', 'admin'])]
public readonly int $id,
#[Groups(['public', 'admin'])]
public readonly string $name,
#[Groups(['admin'])]
public readonly string $email,
#[Groups(['admin'])]
public readonly AccountStatus $status,
#[Groups(['public', 'admin'])]
#[SerializedName('created_at')]
public readonly \DateTimeImmutable $createdAt,
) {
}
}
Nothing sensitive is in the public group by default. Adding a new property means choosing a group on purpose, or it simply never shows up in grouped output.
Build the serializer without the framework
The metadata factory needs an AttributeLoader to read those attributes. Normalizer order matters: the more specific normalizers (dates, enums) must come before ObjectNormalizer, which would otherwise try to treat them as plain objects.
<?php
use App\Dto\AccountStatus;
use App\Dto\AccountView;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\BackedEnumNormalizer;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
$serializer = new Serializer(
[
new DateTimeNormalizer(),
new BackedEnumNormalizer(),
new ObjectNormalizer(new ClassMetadataFactory(new AttributeLoader())),
],
[new JsonEncoder()],
);
$account = new AccountView(
7,
'Ada',
'ada@example.com',
AccountStatus::Active,
new \DateTimeImmutable('2026-01-15T10:00:00+00:00'),
);
echo $serializer->serialize($account, 'json', [
AbstractNormalizer::GROUPS => ['public'],
]);
// {"id":7,"name":"Ada","created_at":"2026-01-15T10:00:00+00:00"}
Swap in ['admin'] and you also get email and status (as the string "active", courtesy of the enum normalizer). The date uses the default RFC 3339 format; pass DateTimeNormalizer::FORMAT_KEY in the context if you need something else.
Make the group a decision, not a default
In a controller I wrap this in one small method that takes the group from the caller's permissions, so the choice lives in exactly one place:
<?php
public function render(AccountView $view, bool $isAdmin): string
{
return $this->serializer->serialize($view, 'json', [
AbstractNormalizer::GROUPS => [$isAdmin ? 'admin' : 'public'],
]);
}
I traced this by hand against the docs rather than running it, so check the exact output in your own project before relying on it.
The gotchas
If you forget the groups context key entirely, the serializer outputs every readable property, grouped or not. That is the opposite of the safe default, so I never call serialize() on these DTOs directly; I go through the wrapper. A unit test that serializes with ['public'] and asserts the absence of email costs five lines and catches the regression that matters. Also keep the DTO separate from your entity: groups reduce leakage, but a dedicated view object means a database column can never reach the response unless you map it explicitly.