AfterPageUriGeneratedEvent
New in version 14.2 Feature: #92780 - Introduce event after page URI generation
The PSR-14 event
\TYPO3\
is dispatched in
Page. It
provides access to the generated URI and the arguments passed to
generate. Listeners can inspect and replace the generated URI. The
parameters payload reflects the sanitized query arguments after handling of
special parameters like
id
and
_language
.
Page is called from many different contexts
across TYPO3 Core, not only during frontend page rendering. This event
therefore fires for URIs generated in the backend (page preview, FormEngine,
new-record redirects), workspace preview links, XML sitemaps, redirect source
detection, webhook payloads, and error handlers, among others.
Listeners that modify the URI must therefore be context-aware. Use
get (see
Router) to
distinguish between an absolute URL (
Router)
and an absolute path (
Router), and use
get,
get, or
get to limit
modifications to the intended context. When replacing the URI, listeners
must ensure that the returned URI is valid in their setup and remains
routable.
Attention
Unconditionally replacing URIs can break backend previews, sitemaps, or other subsystems in non-obvious ways.
Example: Add a tracking parameter to absolute URLs of one site
The following listener appends a tracking query parameter to absolute URLs generated for one specific site, demonstrating both the context-aware scoping described above and how to actually replace the generated URI:
<?php
declare(strict_types=1);
namespace MyVendor\MyExtension\EventListener;
use TYPO3\CMS\Core\Attribute\AsEventListener;
use TYPO3\CMS\Core\Routing\Event\AfterPageUriGeneratedEvent;
use TYPO3\CMS\Core\Routing\RouterInterface;
#[AsEventListener('my-extension/modify-absolute-page-uri')]
final readonly class ModifyAbsolutePageUriListener
{
private const TRACKED_SITE_IDENTIFIER = 'main-site';
public function __invoke(AfterPageUriGeneratedEvent $event): void
{
// Be context-aware: a utm_source parameter only makes sense on a
// fully-qualified URL meant for external use, not on the backend
// previews, sitemaps, redirects and other contexts this event
// also fires for.
if ($event->getType() !== RouterInterface::ABSOLUTE_URL) {
return;
}
// Only add it for the site this campaign targets.
if ($event->getSite()->getIdentifier() !== self::TRACKED_SITE_IDENTIFIER) {
return;
}
// Append a tracking query parameter to the generated URI
$uri = $event->getUri();
parse_str($uri->getQuery(), $queryParameters);
$queryParameters['utm_source'] = 'newsletter';
$uri = $uri->withQuery(http_build_query($queryParameters));
$event->setUri($uri);
}
}