{"id":12706,"library":"ziggy-js","title":"Ziggy.js - Laravel Routes in JavaScript","description":"Ziggy provides a JavaScript `route()` function that seamlessly integrates with Laravel's named routes, enabling consistent URL generation in frontend applications. The current stable version is 2.6.2, and the package maintains an active release cadence with frequent patch and minor updates, reflecting ongoing development and support. Its core differentiator lies in its ability to dynamically expose Laravel's PHP-defined routes to the JavaScript environment via a Blade directive, eliminating the need to hardcode URLs or duplicate routing logic. This integration includes support for advanced Laravel features such as route-model binding, automatic handling of query parameters, and robust TypeScript definitions for a type-safe development experience. Ziggy aims to simplify the development of single-page applications (SPAs) and traditional frontend projects by ensuring that frontend routing logic remains synchronized with the backend.","status":"active","version":"2.6.2","language":"javascript","source_language":"en","source_url":"https://github.com/tighten/ziggy","tags":["javascript","laravel","routes","ziggy","typescript"],"install":[{"cmd":"npm install ziggy-js","lang":"bash","label":"npm"},{"cmd":"yarn add ziggy-js","lang":"bash","label":"yarn"},{"cmd":"pnpm add ziggy-js","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary function to generate URLs. For global usage when using the Blade directive, it's often available directly as `route()` without explicit import. Using CommonJS `require` can lead to issues with module resolution or runtime errors in modern environments.","wrong":"const { route } = require('ziggy-js');","symbol":"route","correct":"import { route } from 'ziggy-js';"},{"note":"The `Router` class provides more advanced control over route generation and manipulation, particularly useful for custom setups or testing. Stick to named imports for ESM compatibility.","wrong":"const Router = require('ziggy-js').Router;","symbol":"Router","correct":"import { Router } from 'ziggy-js';"},{"note":"This is a TypeScript type for the global Ziggy configuration object. It should be imported using `import type` for type-only imports, especially in environments where type imports are tree-shaken.","wrong":"import { ZiggyConfig } from 'ziggy-js';","symbol":"ZiggyConfig","correct":"import type { ZiggyConfig } from 'ziggy-js';"}],"quickstart":{"code":"declare global {\n  interface Window {\n    Ziggy: {\n      url: string;\n      port: null | number;\n      defaults: Record<string, any>;\n      routes: Record<string, {\n        uri: string;\n        methods: string[];\n        bindings?: Record<string, string>;\n        wheres?: Record<string, string>;\n      }>;\n    };\n  }\n}\n\n// Simulate Ziggy configuration typically injected by Laravel's @routes Blade directive\nwindow.Ziggy = {\n    url: 'https://example.com',\n    port: null,\n    defaults: {},\n    routes: {\n        'home': { uri: '/', methods: ['GET', 'HEAD'] },\n        'posts.index': { uri: 'posts', methods: ['GET', 'HEAD'] },\n        'posts.show': { uri: 'posts/{post}', methods: ['GET', 'HEAD'], wheres: { post: '[^/]+' } },\n        'users.profile': { uri: 'users/{user}', methods: ['GET', 'HEAD'], bindings: { user: 'id' }, wheres: { user: '[^/]+' } },\n        'venues.events.show': { uri: 'venues/{venue}/events/{event}', methods: ['GET', 'HEAD'], wheres: { venue: '[^/]+', event: '[^/]+' } }\n    }\n};\n\nimport { route } from 'ziggy-js';\n\n// Basic usage\nconsole.log('Home route:', route('home').toString());\n// Expected: https://example.com/\n\n// With parameters\nconsole.log('Post show (ID 1):', route('posts.show', { post: 1 }).toString());\n// Expected: https://example.com/posts/1\n\n// Multiple parameters\nconsole.log('Venue 1 Event 2:', route('venues.events.show', { venue: 1, event: 2 }).toString());\n// Expected: https://example.com/venues/1/events/2\n\n// Parameters with query strings\nconsole.log('Post show with query:', route('posts.show', { post: 1, page: 2, sort: 'asc' }).toString());\n// Expected: https://example.com/posts/1?page=2&sort=asc\n\n// Route model binding (since v2.6.0)\nconst user = { id: 5, name: 'Alice' }; // Simulate a Laravel model object\nconsole.log('User profile (ID 5):', route('users.profile', user).toString());\n// Expected: https://example.com/users/5\n\n// Simplified current route check (route().current() typically uses window.location)\nconst isCurrentRoute = (path: string, routeName: string, params: Record<string, any>) => {\n    const generatedPath = route(routeName, params, false).relative(); // Get relative path\n    return path === generatedPath; // Simple path match\n};\nconsole.log(`Is '/posts/1' the current 'posts.show' route? ${isCurrentRoute('/posts/1', 'posts.show', { post: 1 })}`);\n// Expected: Is '/posts/1' the current 'posts.show' route? true","lang":"typescript","description":"This quickstart demonstrates how to use Ziggy's `route()` function to generate URLs for Laravel named routes in JavaScript, including handling parameters, multiple parameters, query strings, and basic route model binding. It simulates the `window.Ziggy` global configuration that Laravel injects."},"warnings":[{"fix":"Use the `except` or `only` options with the `@routes` Blade directive (e.g., `@routes(['only' => ['web.*']])`) or the `php artisan ziggy:generate` command to explicitly control which routes are published. Utilize route groups for more granular control.","message":"By default, the `@routes` Blade directive exposes all Laravel routes and their parameters to the frontend HTML. This can be a security concern if sensitive backend routes (e.g., admin panels, internal APIs) are inadvertently exposed. Review and filter routes carefully.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Test your application's routes involving complex query parameters after upgrading to v2.6.0. Most common use cases should be unaffected, but review if you encounter unexpected URL structures.","message":"In v2.6.0, the internal `qs` library for query string parsing and serialization was replaced. While typically an internal change, it *could* subtly alter query string behavior for very specific edge cases if you were relying on particular `qs` encoding/decoding characteristics.","severity":"breaking","affected_versions":">=2.6.0"},{"fix":"Run `php artisan ziggy:generate --json` to output the route configuration to a JSON file. Import this file into your frontend application and initialize Ziggy's `route()` function with it: `import { route } from 'ziggy-js'; import Ziggy from '@/ziggy.json'; route.setZiggy(Ziggy);`","message":"For Single Page Applications (SPAs) or projects with separate frontend repositories, the `Ziggy` configuration must be explicitly generated and imported, as the `@routes` Blade directive will not automatically inject it.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Upgrade Ziggy to version 2.6.0 or higher to leverage route model binding functionality in your JavaScript routes. Ensure your Laravel backend is also up-to-date to fully support model binding features.","message":"Support for Laravel's route model binding and interfaces was introduced in v2.6.0. Applications relying on route model binding to automatically resolve parameters based on model instances will not function correctly with Ziggy versions prior to 2.6.0.","severity":"breaking","affected_versions":"<2.6.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `@routes` is included in your main Blade layout file (e.g., `app.blade.php`) before any JavaScript that uses Ziggy, typically within the `<head>` or at the start of `<body>`.","cause":"The global `route()` function was not initialized because the `@routes` Blade directive was omitted or placed incorrectly.","error":"ReferenceError: route is not defined"},{"fix":"For ES Module environments, use `import { route } from 'ziggy-js';`. If using a bundler, ensure your configuration correctly handles ES Modules. If your project strictly uses CommonJS, consider transpilation or adjusting your build setup as `ziggy-js` is primarily designed for ESM.","cause":"This error often occurs when attempting to use a CommonJS `require()` statement or an incorrect named import syntax for `ziggy-js` in an environment expecting ES Modules.","error":"TypeError: (0, ziggy_js_1.route) is not a function"},{"fix":"Double-check the route name against your Laravel `web.php` or `api.php` files. Verify your `php artisan ziggy:generate` command or `@routes` Blade directive parameters (`except`, `only`, `group`) are not inadvertently excluding the required route.","cause":"The specified route name either does not exist in your Laravel application, was misspelled, or was filtered out when Ziggy's configuration was generated.","error":"The route [your.route.name] is not found."}],"ecosystem":"npm"}