Skip to main content
Instead of generating a static configuration file, you can create an API endpoint that serves Ziggy’s configuration dynamically. This approach is particularly useful for SPAs or applications where the frontend is in a separate repository.

Overview

Serving Ziggy’s configuration from an API endpoint provides several benefits:
  • Always up-to-date: No need to regenerate static files when routes change
  • Dynamic filtering: Serve different routes based on authentication or user permissions
  • Simplified deployment: No need to copy config files between projects
  • Cache control: Implement custom caching strategies

Creating the Basic Endpoint

1

Add the API route

Create a route that returns a new Ziggy instance as JSON:
This endpoint will be available at /api/ziggy.
2

Test the endpoint

Visit the endpoint in your browser or use curl:
You should see a JSON response like:
3

Fetch from your frontend

Fetch the configuration when your application initializes:

Advanced Configurations

Filtering Routes

Serve only specific routes to your frontend:
Or exclude certain routes:

Using Groups

Serve different route groups based on user permissions:
Define groups in config/ziggy.php:

Adding Cache Headers

Implement caching to reduce server load:

Authenticated Endpoint

Protect the endpoint with authentication:

Frontend Integration

React Hook Example

Create a custom hook to fetch and manage Ziggy config:
Use in your components:

Vue Composable Example

Global Configuration Strategy

Load the config once and make it globally available:
Then use it anywhere without passing config:

Performance Optimization

Server-Side Caching

Cache the Ziggy config to avoid regenerating it on every request:
Invalidate the cache when routes change:

Client-Side Caching

Cache the config in localStorage:

ETags for Cache Validation

Troubleshooting

Ensure the route is properly defined:
Verify the route appears in the list. If not, clear the route cache:
If your frontend is on a different domain, configure CORS:
Check your route filtering configuration:
If using Sanctum or other authentication:

Security Considerations

  • Filter sensitive routes: Never expose admin or internal routes to public endpoints
  • Rate limiting: Apply rate limiting to prevent abuse
  • Authentication: Consider requiring authentication for production apps
  • CORS: Only allow trusted origins in production

Best Practices

  1. Cache aggressively: Route configurations rarely change, so cache liberally
  2. Use groups: Filter routes appropriately for different user types
  3. Version your endpoint: Consider versioning (e.g., /api/v1/ziggy) for future changes
  4. Monitor performance: Track endpoint response times and cache hit rates
  5. Handle errors gracefully: Provide fallbacks if config loading fails