Modern applications often rely on configuration flags to control which features are accessible in different contexts. Instead of modifying controller logic or maintaining separate code branches, Symfony allows routing behavior to be driven directly by configuration values. This makes it possible to activate or deactivate endpoints depending on environment-specific settings. This tutorial explains how to make route available based on environment variable in Symfony 8 application.
In Symfony, routes can be restricted using conditional expressions. By leveraging environment variables, feature availability can be controlled without changing application code. This approach is particularly useful for feature toggles, beta functionality, staged rollouts.
Let's say we have environment variable which defines feature mode. Changing its value will allow enable or disable specific routes.
.env
FEATURE_MODE=beta
Symfony routing system provides a condition option. This option accepts an expression that must evaluate to true for the route to be matched. To ensure a route is available only when FEATURE_MODE is set to beta, the env expression function can be used within the route condition.
src/Controller/BetaController.php
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class BetaController
{
#[Route('/beta', name: 'beta', condition: "env('FEATURE_MODE') === 'beta'")]
public function index(): Response
{
return new Response();
}
}
config/routes.yaml
beta:
path: /beta
controller: App\Controller\BetaController::index
condition: "env('FEATURE_MODE') === 'beta'"
Leave a Comment
Cancel reply