Define Stateless Route in Symfony 8

Define Stateless Route in Symfony 8

As Symfony application grow, performance and HTTP caching often become critical concerns. One common pitfall is unintended session usage. Even a single interaction with the session can cause Symfony to mark the response as private non-cacheable. Symfony provides a clean solution for this scenario: stateless routes. This tutorial explains how to define stateless route in Symfony 8 application.

By marking a route as stateless, we explicitly tell Symfony that the session must not be used when handling requests for that route. This helps enforce correct behavior and makes caching strategies more predictable.

A stateless route guarantees that no session is accessed during the request lifecycle. If the application accidentally tries to use the session anyway, Symfony can alert us:

  • kernel.debug = true (dev environment) - will throw an UnexpectedSessionUsageException exception.
  • kernel.debug = false (prod environment) - will log a warning.

We can declare a route as stateless using stateless bool option. In this example, the route is explicitly marked as stateless. Even though the controller tries to use the session to set a value. Symfony will detect this wrong usage and either raise an exception during development or log a warning in production.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController
{
    #[Route('/', stateless: true)]
    public function index(Request $request): Response
    {
        $request->getSession()->set('name', 'John');

        return new Response();
    }
}

config/routes.yaml

test_index:
    path: /
    controller: App\Controller\TestController::index
    stateless: true

Leave a Comment

Cancel reply

Your email address will not be published.