Claude Skill

ux-router

Symfony UX Router: generate Symfony route URLs in JavaScript, like path() and url() in Twig, type-checked in TypeScript. Use for createRouter, exposing routes (ux_router.routes, expose option), var/routes, ux:router:warm-cache.

LLM Mart · 0 points · 0 views 0 listing impressions 0 install-command copies
Download smnandre-symfony-ux-skills-skills_ux-router-78c25ed.zip · 2 KB

Install

skills CLI npx skills add https://github.com/smnandre/symfony-ux-skills/tree/main/skills/ux-router
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install smnandre-symfony-ux-skills@llmmart
Git git clone https://github.com/smnandre/symfony-ux-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole smnandre/symfony-ux-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

UX Router

Generate the URLs of your Symfony routes in JavaScript, with the same result as the path() and url() Twig functions. Exposed routes are dumped to var/routes/; with TypeScript, route names and parameters are type-checked.

Since Symfony UX 3.6+. The package is experimental: its API may still change.

Prefer passing URLs from Twig (a Stimulus value, a data-* attribute) when a controller needs one or two fixed URLs. Reach for UX Router when JavaScript builds URLs from data it only knows at runtime.

Installation

composer require symfony/ux-router

Flex creates the router module:

// assets/router.js (rename to router.ts for type-checking)
import { createRouter } from '@symfony/ux-router';
import { routes, defaultLocale } from '../var/routes/index.js';

export const { path, url } = createRouter({ routes, defaultLocale });
Asset pipeline Extra step
AssetMapper None: the bundle registers the dump directory and the @symfony/ux-router importmap entry
Reprise (Vite / Rsbuild) npm install --force, then restart the dev server
Webpack Encore npm install --force, then restart Encore

Exposing Routes

No route is exposed by default. List name patterns:

# config/packages/ux_router.yaml
ux_router:
    routes:
        - 'app_*'          # wildcard
        - '!app_admin_*'   # leading ! excludes

A single route can opt in or out with the expose option, which always wins over the patterns:

#[Route('/search', name: 'search', options: ['expose' => true])]
public function search(): Response

A localized route is exposed when its name (app_about) or one of its variants (app_about.en) matches.

Exposed routes are readable by anyone who loads your JavaScript, and they all end up in the bundle. Keep the list to what JavaScript calls; avoid '*', which also exposes internal routes such as the profiler's.

Generating URLs

import { path, url } from './router.js';

path('app_blog_show', { slug: 'hello', _query: { page: 2 }, _fragment: 'comments' });
// '/blog/hello?page=2#comments'

path('app_blog_show', { slug: 'hello' }, true);
// relative path: 'blog/hello'

url('app_blog_show', { slug: 'hello' });
// 'https://example.com/blog/hello'

url('app_blog_show', { slug: 'hello' }, true);
// network path: '//example.com/blog/hello'

Query parameters go in _query. Optional parameters equal to their default are omitted, as in PHP.

Localized Routes

Call a localized route by its base name; the current locale picks the variant:

path('app_about');                    // '/about' when <html lang="en">
path('app_about', { _locale: 'fr' }); // '/a-propos'

Locale resolution order: the _locale parameter of the call, the _locale of the context given to createRouter(), the lang attribute of <html> (fr-FR becomes fr_FR), the defaultLocale option (the dump exports framework.default_locale), then en.

Request Context

Host, scheme and port come from the current page. Override them with context, for instance for an app served from a sub-directory:

export const { path, url } = createRouter({
    routes,
    context: { baseUrl: '/my-app' },
});

Errors

RouteNotFoundError, MissingMandatoryParametersError and InvalidParameterError are exported by @symfony/ux-router and thrown in the same cases as in PHP:

import { RouteNotFoundError } from '@symfony/ux-router';

try {
    path('app_unknown');
} catch (error) {
    if (error instanceof RouteNotFoundError) {
        // ...
    }
}

Requirements are checked as JavaScript regexes ([^/]+ instead of [^/]++); a requirement JavaScript cannot express, such as \A or [[:alpha:]], is left to the PHP router.

Dumping

Routes are dumped on cache warmup, and again in dev on the next request after a route changes. To refresh only the JavaScript routes:

php bin/console ux:router:warm-cache

Configuration

# config/packages/ux_router.yaml
ux_router:
    # Where routes and TypeScript types are dumped (update assets/router.js if changed)
    dump_directory: '%kernel.project_dir%/var/routes'

    # Dump TypeScript types next to the routes
    dump_typescript: true

    # Route name patterns to expose, "!" to exclude
    routes: []

AssetMapper ignores the TypeScript types, so they can be skipped in production there:

when@prod:
    ux_router:
        dump_typescript: false

Keep them with Reprise or Encore and TypeScript: the build type-checks against them.

Gotchas

  • RouteNotFoundError for an existing route: the route is hidden from JavaScript. Check the routes patterns (an exclusion may match) or add options: ['expose' => true].
  • Stale routes after a change in production: the dump happens on cache warmup; deploy with cache:warmup or run ux:router:warm-cache.
  • Wrong host or base path behind a proxy or in a sub-directory: pass context to createRouter().
  • TypeScript errors on route names: the types come from the dump; run ux:router:warm-cache after adding a route.

References

See Also

  • stimulus: import path() in a controller to build URLs from targets or values
  • turbo: Turbo.visit(path('app_blog_show', { slug })) navigates with Drive
  • ux-translator: same dump model for translations (var/translations/, trans() in JavaScript)
Files (symfony-ux-skills)
  • SKILL.md 6.1 KB
    ---
    name: ux-router
    description: 'Symfony UX Router: generate Symfony route URLs in JavaScript, like path() and url() in Twig, type-checked in TypeScript. Use for createRouter, exposing routes (ux_router.routes, expose option), var/routes, ux:router:warm-cache.'
    license: MIT
    metadata:
      author: Simon André
      url: https://smnandre.dev
    ---
    
    # UX Router
    
    Generate the URLs of your Symfony routes in JavaScript, with the same result as the `path()` and `url()` Twig functions. Exposed routes are dumped to `var/routes/`; with TypeScript, route names and parameters are type-checked.
    
    Since Symfony UX 3.6+. The package is **experimental**: its API may still change.
    
    Prefer passing URLs from Twig (a Stimulus value, a `data-*` attribute) when a controller needs one or two fixed URLs. Reach for UX Router when JavaScript builds URLs from data it only knows at runtime.
    
    ## Installation
    
    ```bash
    composer require symfony/ux-router
    ```
    
    Flex creates the router module:
    
    ```javascript
    // assets/router.js (rename to router.ts for type-checking)
    import { createRouter } from '@symfony/ux-router';
    import { routes, defaultLocale } from '../var/routes/index.js';
    
    export const { path, url } = createRouter({ routes, defaultLocale });
    ```
    
    | Asset pipeline | Extra step |
    |----------------|------------|
    | AssetMapper | None: the bundle registers the dump directory and the `@symfony/ux-router` importmap entry |
    | Reprise (Vite / Rsbuild) | `npm install --force`, then restart the dev server |
    | Webpack Encore | `npm install --force`, then restart Encore |
    
    ## Exposing Routes
    
    No route is exposed by default. List name patterns:
    
    ```yaml
    # config/packages/ux_router.yaml
    ux_router:
        routes:
            - 'app_*'          # wildcard
            - '!app_admin_*'   # leading ! excludes
    ```
    
    A single route can opt in or out with the `expose` option, which always wins over the patterns:
    
    ```php
    #[Route('/search', name: 'search', options: ['expose' => true])]
    public function search(): Response
    ```
    
    A localized route is exposed when its name (`app_about`) or one of its variants (`app_about.en`) matches.
    
    Exposed routes are readable by anyone who loads your JavaScript, and they all end up in the bundle. Keep the list to what JavaScript calls; avoid `'*'`, which also exposes internal routes such as the profiler's.
    
    ## Generating URLs
    
    ```javascript
    import { path, url } from './router.js';
    
    path('app_blog_show', { slug: 'hello', _query: { page: 2 }, _fragment: 'comments' });
    // '/blog/hello?page=2#comments'
    
    path('app_blog_show', { slug: 'hello' }, true);
    // relative path: 'blog/hello'
    
    url('app_blog_show', { slug: 'hello' });
    // 'https://example.com/blog/hello'
    
    url('app_blog_show', { slug: 'hello' }, true);
    // network path: '//example.com/blog/hello'
    ```
    
    Query parameters go in `_query`. Optional parameters equal to their default are omitted, as in PHP.
    
    ## Localized Routes
    
    Call a localized route by its base name; the current locale picks the variant:
    
    ```javascript
    path('app_about');                    // '/about' when <html lang="en">
    path('app_about', { _locale: 'fr' }); // '/a-propos'
    ```
    
    Locale resolution order: the `_locale` parameter of the call, the `_locale` of the `context` given to `createRouter()`, the `lang` attribute of `<html>` (`fr-FR` becomes `fr_FR`), the `defaultLocale` option (the dump exports `framework.default_locale`), then `en`.
    
    ## Request Context
    
    Host, scheme and port come from the current page. Override them with `context`, for instance for an app served from a sub-directory:
    
    ```javascript
    export const { path, url } = createRouter({
        routes,
        context: { baseUrl: '/my-app' },
    });
    ```
    
    ## Errors
    
    `RouteNotFoundError`, `MissingMandatoryParametersError` and `InvalidParameterError` are exported by `@symfony/ux-router` and thrown in the same cases as in PHP:
    
    ```javascript
    import { RouteNotFoundError } from '@symfony/ux-router';
    
    try {
        path('app_unknown');
    } catch (error) {
        if (error instanceof RouteNotFoundError) {
            // ...
        }
    }
    ```
    
    Requirements are checked as JavaScript regexes (`[^/]+` instead of `[^/]++`); a requirement JavaScript cannot express, such as `\A` or `[[:alpha:]]`, is left to the PHP router.
    
    ## Dumping
    
    Routes are dumped on cache warmup, and again in `dev` on the next request after a route changes. To refresh only the JavaScript routes:
    
    ```bash
    php bin/console ux:router:warm-cache
    ```
    
    ## Configuration
    
    ```yaml
    # config/packages/ux_router.yaml
    ux_router:
        # Where routes and TypeScript types are dumped (update assets/router.js if changed)
        dump_directory: '%kernel.project_dir%/var/routes'
    
        # Dump TypeScript types next to the routes
        dump_typescript: true
    
        # Route name patterns to expose, "!" to exclude
        routes: []
    ```
    
    AssetMapper ignores the TypeScript types, so they can be skipped in production there:
    
    ```yaml
    when@prod:
        ux_router:
            dump_typescript: false
    ```
    
    Keep them with Reprise or Encore and TypeScript: the build type-checks against them.
    
    ## Gotchas
    
    - **`RouteNotFoundError` for an existing route**: the route is hidden from JavaScript. Check the `routes` patterns (an exclusion may match) or add `options: ['expose' => true]`.
    - **Stale routes after a change in production**: the dump happens on cache warmup; deploy with `cache:warmup` or run `ux:router:warm-cache`.
    - **Wrong host or base path behind a proxy or in a sub-directory**: pass `context` to `createRouter()`.
    - **TypeScript errors on route names**: the types come from the dump; run `ux:router:warm-cache` after adding a route.
    
    ## References
    
    - [Symfony UX package page](https://ux.symfony.com/router) ([Markdown summary](https://ux.symfony.com/router.md)) · [`symfony/ux-router` on Packagist](https://packagist.org/packages/symfony/ux-router).
    - Try the [JavaScript routing demo](https://ux.symfony.com/router#demo).
    - For route exposure, URL generation and TypeScript, see the [Symfony UX Router documentation](https://symfony.com/bundles/ux-router).
    
    ## See Also
    
    - **stimulus**: import `path()` in a controller to build URLs from targets or values
    - **turbo**: `Turbo.visit(path('app_blog_show', { slug }))` navigates with Drive
    - **ux-translator**: same dump model for translations (`var/translations/`, `trans()` in JavaScript)
    

Comments

Sign in to join the conversation.

No comments yet. Start the conversation.

Reviews (0)

No reviews yet.