Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Javascript Routing Laravel Package

becklyn/javascript-routing

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require becklyn/javascript-routing
    

    Add to config/bundles.php:

    return [
        // ...
        Becklyn\JavaScriptRoutingBundle\BecklynJavaScriptRoutingBundle::class => ['all' => true],
    ];
    
  2. Enable Routing Endpoint Import the routes in config/routes.yaml:

    _import.becklyn_javascript_routing:
        resource: '@BecklynJavaScriptRoutingBundle/Resources/config/routes.yaml'
        prefix: /_v/routing
    

    (Default prefix: /_v/routing)

  3. First Use Case Fetch routes in JavaScript:

    fetch('/_v/routing')
        .then(response => response.json())
        .then(routes => console.log(routes));
    

    Outputs a structured array of Symfony routes with metadata (e.g., paths, methods, requirements).


Implementation Patterns

Core Workflows

  1. Frontend Routing Integration

    • Use the endpoint to dynamically generate client-side routes (e.g., for SPAs or progressive enhancement).
    • Example: Replace hardcoded links with JavaScript-generated ones:
      const route = routes.find(r => r.path === '/dashboard');
      document.getElementById('dashboard-link').href = route.path;
      
  2. Conditional Route Loading

    • Load only routes needed for the current page (e.g., via requirements or defaults):
      const activeRoutes = routes.filter(r =>
          r.requirements.user_role === 'admin' ||
          r.path === window.location.pathname
      );
      
  3. Route-Based Feature Flags

    • Enable/disable UI elements based on available routes:
      if (routes.some(r => r.path === '/admin')) {
          document.getElementById('admin-panel').style.display = 'block';
      }
      

Integration Tips

  • Cache the Response Cache the /_v/routing endpoint (e.g., with Symfony’s HTTP cache) to avoid repeated requests:

    # config/packages/framework.yaml
    framework:
        http_cache:
            cache_control:
                rules:
                    - path: ^/_v/routing
                      max_age: 3600  # Cache for 1 hour
    
  • Extend Route Data Add custom metadata to routes via Symfony’s Route object:

    # config/routes.yaml
    app_home:
        path: /
        controller: App\Controller\HomeController::index
        becklyn_js_routing:
            data:
                priority: high  # Custom field for JS logic
    
  • Versioning Use the _v prefix to version routes (e.g., /_v/2/routing) and update incrementally.


Gotchas and Tips

Pitfalls

  1. Route Name vs. Path Conflicts

    • The bundle exposes paths, not route names. Ensure paths are unique or handle collisions in JS:
      // Avoid: routes.find(r => r.name === 'app_home') // ❌ Uses names (not exposed)
      // Use:   routes.find(r => r.path === '/')       // ✅ Uses paths
      
  2. Sensitive Route Exposure

    • All routes (including admin/internal ones) are exposed. Filter them in JS or use Symfony’s requirements:
      app_admin:
          path: /admin
          requirements:
              _js_access: 'true'  # Filter in JS: r.requirements._js_access === 'true'
      
  3. Dynamic Routes

    • Placeholders (e.g., {id}) are preserved but may break JS parsing. Sanitize paths if needed:
      const safePath = route.path.replace(/\{.*?\}/g, '[dynamic]');
      

Debugging

  • Verify Endpoint Check the endpoint returns expected data:

    curl http://localhost/_v/routing | jq
    

    Should output:

    [
        {"path": "/", "methods": ["GET"], "requirements": {...}},
        {"path": "/dashboard", "methods": ["GET"], ...}
    ]
    
  • Symfony Router Issues If routes are missing, ensure:

    • The bundle is enabled in config/bundles.php.
    • No typos in the _import YAML path.

Extension Points

  1. Customize Output Format Override the RouteCollection serializer via a compiler pass or event listener:

    // src/EventListener/RouteSerializerListener.php
    public function onKernelRequest(GetResponseEvent $event) {
        $routes = $event->getRequest()->attributes->get('routes');
        // Transform $routes before JSON encoding
    }
    
  2. Add Route Groups Use Symfony’s route_groups to batch routes with shared JS metadata:

    _js_group:
        path: /
        becklyn_js_routing:
            data:
                group: 'public'
        children:
            app_home: ~
            app_contact: ~
    
  3. Security Protect the endpoint with Symfony’s access control:

    _v_routing:
        path: /_v/routing
        controller: Becklyn\JavaScriptRoutingBundle\Controller\RoutingController::index
        methods: [GET]
        requirements:
            _method: GET
        defaults:
            _controller: 'Becklyn\JavaScriptRoutingBundle\Controller\RoutingController::index'
        access_control: 'public'  # Or restrict to specific roles
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast