Study guide · Sites, Routing and Request
From URL to page: sites, routing and the request in TYPO3
Before TYPO3 renders any HTML, it decides which site, language, page and plugin arguments a URL means. This page follows that path, from middlewares and site configuration to route enhancers, the cHash and sessions.
From request to response
Our example is the site main in German and English. The extension my_extension provides the plugin ConferenceList, a list and a detail view of conferences. A visitor opens this address:
https://example.org/en/conferences/typo3-days-2026.htmlThe bootstrap sets up the environment, then an application takes over. The Core has four of them: one for the frontend, one for the backend including Ajax, one for the command line and one for the Install Tool.
TYPO3\CMS\Frontend\Http\Application
TYPO3\CMS\Backend\Http\Application
TYPO3\CMS\Core\Console\CommandApplication
TYPO3\CMS\Install\Http\ApplicationExtbase has no application of its own. It only starts when TYPO3 meets a plugin while rendering the page.
Next, the request passes through a stack of middlewares following PSR-15. Each middleware can change the request, pass it on or answer itself, for example with a redirect. At the end, the request handler produces the page. The response then travels back, and every middleware can still adjust it.
Writing your own middleware
Our extension determines a region for every visitor. The middleware implements MiddlewareInterface with the method process().
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$region = $request->getQueryParams()['region'] ?? 'de';
$request = $request->withAttribute('myext.region', $region);
return $handler->handle($request);
}PSR-7 requests are immutable. withAttribute() returns a modified copy. Without the assignment you pass on the old request, and the attribute is missing in the controller.
Since TYPO3 14, the Core no longer syncs the superglobals for GET and POST with the request. So read parameters with getQueryParams() from the request you were given. The global request variable is not set yet in early middlewares either. To create your own response, for example JSON, inject the PSR-17 factories ResponseFactoryInterface and StreamFactoryInterface. The Core's response classes are not public API.
You register the middleware in Configuration/RequestMiddlewares.php. Services.yaml only controls dependency injection.
return [
'frontend' => [
'my-extension/region' => [
'target' => \MyVendor\MyExtension\Middleware\RegionResolver::class,
'after' => ['typo3/cms-frontend/site'],
'before' => ['typo3/cms-frontend/page-resolver'],
],
],
];The first level is the stack, frontend or backend. Each middleware has the keys target, before, after and disabled. There is no priority. Without before and after, the middleware ends up at an arbitrary position. The site attribute is only set by the site resolver with the identifier typo3/cms-frontend/site. If you need it, you must run after it.
You can see the sorted list in the module "System", "Configuration" of the lowlevel extension, entry "HTTP Middlewares (PSR-15)". To replace a Core middleware, disable it with disabled and register your own under a new identifier. Only changing the order of a Core middleware can lead to circular dependencies.
Other places to get the request: In an Extbase controller, the property request holds the attributes site and language. A custom ViewHelper gets the request from the rendering context, through the attribute named after the class ServerRequestInterface. The global request variable is a leftover, and makeInstance() cannot return the request, because it is no container service. On the command line there is no request at all.
Environment, configuration and the Context API
The application context describes the environment of the installation. There are three main contexts: Production, Development and Testing. It is set through the environment variable TYPO3_CONTEXT, for example in the web server or in ddev. It is fixed right at the start of the bootstrap. If the variable is missing, Production applies. Testing is reserved for the Core's tests. There is no main context called Staging. For a staging server, use a sub-context of Production:
TYPO3_CONTEXT=Production/StagingIn code, you check it with Environment::getContext(). This returns an ApplicationContext with isDevelopment(), isProduction() and isTesting(). A sub-context like Development Local counts as Development. There is no isDevelopment method directly on Environment.
The Environment class also knows the paths. getProjectPath() is the folder with composer.json, where you might keep a data folder for import files. getPublicPath() is the document root, and everything in it is reachable from the web. getVarPath() lies outside of it and suits temporary files. There are also getConfigPath(), isComposerMode() and isCli(). The method getComposerRootPath() was removed in TYPO3 14, and the version comes from Typo3Version.
An API key that administrators enter under "Extension Configuration" applies to the whole installation. You describe the field in ext_conf_template.txt using the syntax of TypoScript constants:
# cat=basic; type=string; label=API key
apiKey =The value is stored in settings.php in the configuration folder. A service reads it with the injected ExtensionConfiguration and its method get(), passing the extension key and a path. Without a path you get the whole array.
If a download link must contain a file ID that nobody can tamper with, use the HashService. appendHmac() appends a signature made from the encryptionKey and a secret per purpose. validateAndStripHmac() checks it and throws an exception if the value was changed. The old hmac method in GeneralUtility no longer exists in TYPO3 14.
The Context API is something different. It tells you for whom and when the page is being rendered, and it is built anew for each entry point. You get the Context class through dependency injection. It splits its information into aspects:
dateprovides timestamp, iso, timezone and full. accessTime is rounded down to the full minute and meant for access checks.languageprovides id, contentId and the fallback and overlay settings.frontend.userandbackend.userprovide id, username, isLoggedIn, groupIds and groupNames.workspaceprovides id, isLive and isOffline. The live workspace always has the ID 0.visibilitytells whether hidden or deleted records are included.
$now = $this->context->getPropertyFromAspect('date', 'timestamp');
$isLive = $this->context->getPropertyFromAspect('workspace', 'isLive');
$groups = $this->context->getPropertyFromAspect('frontend.user', 'groupIds');
$isMember = in_array(3, $groups, true);For logged-in frontend users, groupIds first contains the pseudo groups 0 and minus 2, then the real groups. Properties like groupId, isInGroup or isDraft do not exist. The default overlay type is OVERLAYS_ON_WITH_FLOATING: translations are overlaid, untranslated records are hidden, and records without a parent in the default language are still shown.
To add your own aspect, write a class that implements AspectInterface with the method get(). Use setAspect() to put it into the context under a name. After that, any code can read it with getPropertyFromAspect().
The site configuration
A site is a branch of the page tree with its own domain, languages and routing rules. Its configuration is a YAML file and belongs in version control. In Composer installations it lives in the folder config, subfolder sites, in a folder named after the identifier. In Classic installations it lives under typo3conf.
# config/sites/main/config.yaml
rootPageId: 1
base: 'https://example.org/'
languages:
- languageId: 0
locale: de_DE.UTF-8
base: /de/
- languageId: 1
locale: en_US.UTF-8
base: /en/
errorHandling:
- errorCode: 404
errorHandler: Page
errorContentSource: 't3://page?uid=123'
baseVariants:
- base: 'https://example.ddev.site/'
condition: 'applicationContext == "Development"'
dependencies:
- typo3/fluid-styled-contentrootPageIdis the UID of the root page, usually marked "Use as Root Page". All subpages belong to the site.baseis the base URL. TYPO3 uses it to match incoming requests to the site and to build all links.- Under
languages, the default language always has languageId 0. Other languages get their own IDs and usually their own path as base. TYPO3 picks the language from the URL, not from the browser. errorHandlingdefines error pages per status code, with the handlers Page, Fluid or PHP. The errorCode 0 covers all other codes. An ErrorDocument in the htaccess file does not work, because the web server only sees a successful request toindex.php.baseVariantsgives a development system a different base URL, using conditions in the Symfony expression language. In base you insert environment variables with the env syntax in percent signs, in the condition with getenv.routesare static routes, for example for robots.txt, with the types staticText, uri or asset.dependenciesincludes site sets.
Your own values: Unknown keys in the YAML file are kept when the site is saved in the backend. You read them with the site's getConfiguration(). To show a field in the Sites module, add it in the file sites.php in the Overrides folder under Configuration/SiteConfiguration, in the columns of the site configuration. This is experimental and meant only for simple fields. The helpers from ExtensionManagementUtility do not work there.
Site sets, settings and the Sites API
A site set is a package in an extension's Configuration/Sets folder. It bundles TypoScript, page TSconfig, settings and, since TYPO3 14.1, route enhancers. A site uses a set by listing its name under dependencies. Nothing is copied, and sets can bring further sets along.
Site settings are typed values per site. Our set defines them in settings.definitions.yaml:
settings:
myext.itemsPerPage:
type: int
default: 10
label: 'Conferences per page'Values changed in the site settings editor are stored in the site's settings.yaml. Once that file exists, only its values apply, and settings in config.yaml are ignored. In TypoScript, site settings are available as constants:
plugin.tx_myext.settings.itemsPerPage = {$myext.itemsPerPage}Sites API: You find other sites with the SiteFinder. A console command, which has no request, injects it and calls getSiteByPageId(). It searches along the rootline and throws a SiteNotFoundException if it finds nothing.
$site = $this->siteFinder->getSiteByPageId(12);
$status = $site->getSettings()->get('redirects.httpStatusCode', 307);
$apiKey = $site->getConfiguration()['apiKey'] ?? '';Domain records no longer exist since the site configuration was introduced. In TypoScript conditions, the function siteLanguage calls the matching getter of the SiteLanguage, and site works the same way. Conditions with globalVar and the parameter L no longer work.
[siteLanguage("languageId") == 1]
[siteLanguage("locale").getLanguageCode() == "en"]Page routing and links
Routing maps a URL to a controller or action and its parameters. It works in both directions: resolving URLs and generating URLs. Speaking URLs are easier to read and help with search engines.
TYPO3 uses Symfony Routing for this. There, a route has a path with placeholders, defaults and requirements. Routes can be defined with a PHP attribute, YAML or PHP. The UrlMatcher matches a URL to a route, and the UrlGenerator creates URLs.
Page routing is always active and needs a site. TYPO3 finds the site by the base URL, the language by the prefix and the page by its slug. That is the field "URL Segment", which holds the full path of the page. It is suggested from the title. The old field alias no longer exists, and the navigation title only affects menus.
If an editor changes the slug and the Core extension redirects is installed, TYPO3 automatically creates a redirect from the old URL to the new one. The site settings autoCreateRedirects and autoUpdateSlugs are both on by default.
Always let TYPO3 build your links. In Fluid, f:link.page with pageUid and f:link.typolink with parameter link to a page with the current slug, domain and language. f:link.external knows nothing about page UIDs. In a service, the site's router generates the URL:
$uri = $site->getRouter()->generateUri(12, ['_language' => 1]);Scheme and host come from the base of the language. Links with id and L date from the time before sites.
Route enhancers and aspects
Without configuration, plugin arguments appear as a query string, usually with a cHash. Route enhancers under routeEnhancers turn them into a readable path and translate it back on the way in. The Core provides:
- Simple for plain parameters without a namespace, such as category.
- Plugin for parameters in a namespace like tx_myext.
- Extbase, which also knows controller and action.
- PageType as a decorator. It adds a suffix such as html or json.
routeEnhancers:
Conferences:
type: Extbase
limitToPages: [12]
extension: MyExtension
plugin: ConferenceList
routes:
- routePath: '/page/{page}'
_controller: 'Conference::list'
- routePath: '/{conference-title}'
_controller: 'Conference::show'
_arguments:
conference-title: conference
defaults:
page: '1'
aspects:
conference-title:
type: PersistedAliasMapper
tableName: tx_myextension_domain_model_conference
routeFieldName: path_segment
page:
type: StaticRangeMapper
start: '1'
end: '100'
PageTypeSuffix:
type: PageType
default: '.html'
map:
'.html': 0
'feed.xml': 13_controller names controller and action without their suffixes. _arguments maps placeholders to the action's arguments. A placeholder without a default is mandatory, and only defaults makes it optional. For page 1 you then get the short URL without a number. requirements restricts the allowed values.
Aspects each handle one placeholder. Mappers translate values. StaticValueMapper uses a fixed list, and StaticRangeMapper a number range. PersistedAliasMapper reads a database field such as the slug, and PersistedPatternMapper a pattern of several fields. The modifier LocaleModifier replaces a fixed path segment per language, for example uebersicht and overview. Its localeMap assigns a value to locale patterns, and default covers the rest.
In short: an enhancer describes the additional path with placeholders. A decorator only appends something to the finished route. A mapper maps a single placeholder value.
New in TYPO3 14: Site sets can bring route enhancers in a route-enhancers.yaml, and the site configuration always wins. That is how the set typo3 seo-sitemap provides the route for sitemap.xml. And since 14.2, limitToPages also accepts expressions, with all entries combined by or:
limitToPages:
- 'page["doktype"] == 1'Your own enhancer: The class extends AbstractEnhancer. You register it in ext_localconf.php in the routing enhancers section of the global configuration under the name MyEnhancer and use it with type MyEnhancer. Your own aspects go under routing aspects.
Performance and SEO: Persisted mappers query the database every time they resolve or generate a URL. Several URLs for the same content create duplicate content, and a canonical tag helps against that. Parameters without a mapper lead to URLs with a cHash.
The cHash
The page cache stores variants of a page per parameter. With random values, an attacker could flood the cache. That is why the cHash signs the cache-relevant parameters with the secret encryptionKey. Only a valid cHash creates a cache variant of its own.
If the cHash for a plugin parameter is missing or wrong, TYPO3 returns a 404 error. This is due to pageNotFoundOnCHashError, which is on by default. So always let TYPO3 build your links. If a search term should not count, add it to excludedParameters:
$GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludedParameters'][] = 'tx_search_pi1[query]';With a caret in front, an entry covers all parameters that start the same way.
Readable URLs without a cHash are only possible if TYPO3 knows the values or checks them strictly. The first way is aspects such as StaticValueMapper or PersistedAliasMapper. The second way is the option static for a placeholder, together with a strict requirements rule. Without that rule, TYPO3 ignores static, and the cHash stays.
Sessions
A session links several requests of one visitor. The cookie fe_typo_user in the frontend or be_typo_user in the backend holds only the session ID. By default, the data lives in the tables fe_sessions and be_sessions. The ID is stored there only as a hash, so a database leak does not help anyone take over sessions.
The Core ships the DatabaseSessionBackend as the default and the RedisSessionBackend. Since TYPO3 14.2, Redis has separate options for username and password. Configuration lives in the SYS session section of the global configuration, split into FE and BE. Custom backends implement SessionBackendInterface.
UserSessionManager::create() with FE creates the manager that loads, validates and stores UserSession objects. When a user logs out, TYPO3 ends the session and removes its data. Logging in again gives a new ID.
Our shopping cart for guests uses the type ses. This data belongs to the session, even without a login.
$user = $request->getAttribute('frontend.user');
$user->setKey('ses', 'myext_cart', $data);
$user->storeSessionData();Key points
- Frontend, backend, command line and Install Tool each have an application, Extbase does not.
- Middlewares go into
Configuration/RequestMiddlewares.phpwith target, before, after and disabled. - Requests are immutable. You must assign the result of withAttribute.
- The application context describes the environment, the Context API describes the current request.
- The site is a YAML file with rootPageId, base, languages, errorHandling, routes and dependencies.
- The set defines site settings, and in TypoScript they are constants.
- Enhancers make plugin arguments readable, aspects translate placeholders, PageType adds a suffix.
- Without known values, a URL needs a valid cHash, otherwise you get a 404 error.
- Session data needs
storeSessionData().
Terms
- Application context
- Environment of the installation, set through TYPO3_CONTEXT.
- Aspect in the context
- Part of the Context API with information about the request, such as date or user.
- Aspect in routing
- Translates one placeholder of a route, as a mapper or modifier.
- cHash
- Signature of the cache-relevant URL parameters.
- Decorator
- Appends something to the finished route, such as a suffix.
- Middleware
- PSR-15 building block that processes request and response.
- Route enhancer
- Extends the page URL with readable plugin arguments.
- Site set
- Reusable configuration package of an extension.
- Slug
- Readable URL segment of a page or record.