route() function through the NPM package.
Overview
For JavaScript projects managed separately from Laravel (without Composer or avendor directory), Ziggy provides an NPM package that gives you access to the same powerful routing functionality.
Installation
Choose your config delivery method
You have two options for making your Laravel routes available to your frontend:
- Option A: Generate a static config file and add it to your frontend project
- Option B: Create an API endpoint that serves the config dynamically
Option A: Using a Generated Config File
Generating the Config
On your Laravel backend, run the Ziggy generate command:resources/js/ziggy.js file with your routes configuration:
Copying to Your Frontend Project
Copy this file to your frontend project and import it where needed:Option B: API Endpoint Configuration
For dynamic configuration that doesn’t require copying files between projects, create an API endpoint that serves Ziggy’s config.Creating the Endpoint
Add a route to your Laravel API:Fetching Config from the Frontend
Fetch the config when your app initializes:Framework-Specific Usage
React Example
Vue Example
Making Config Available Globally
To avoid passing the Ziggy config to everyroute() call, you can make it globally available:
route() function without passing the config:
Troubleshooting
Routes Not Found
If theroute() function can’t find your routes:
- Verify the config is loaded: Check that your Ziggy config object contains the expected routes
- Check route names: Ensure you’re using the exact route name as defined in Laravel
- Regenerate config: If using a static file, regenerate it after adding new routes
CORS Issues with API Endpoint
If fetching config from an API endpoint fails with CORS errors:- Configure CORS in Laravel:
- Verify endpoint is accessible: Test the endpoint directly in your browser
Incorrect Base URLs
If generated URLs use the wrong domain:- Check APP_URL: Ensure your
.envfile has the correctAPP_URL - Verify Ziggy config URL: Check the
urlproperty in your Ziggy config matches your API domain
TypeScript Configuration
For TypeScript projects, configure path aliases intsconfig.json:
Best Practices
Keep Config in Sync
Keep Config in Sync
- Set up automated regeneration when routes change (see Auto-Regeneration Guide)
- Or use the API endpoint approach for always up-to-date config
- Consider caching the API endpoint response in production
Filter Sensitive Routes
Filter Sensitive Routes
- Use Ziggy’s filtering to exclude admin or internal routes
- Only expose public API routes to your frontend
Environment-Specific Configuration
Environment-Specific Configuration
- Use different base URLs for development and production
- Consider environment variables for API endpoints