tighten / ziggy

Use your Laravel routes in JavaScript.
MIT License
3.83k stars 247 forks source link

Passing Ziggy configuration to Inertia.js SSR in a Svelte app #734

Closed avanerk closed 5 months ago

avanerk commented 5 months ago

Ziggy version

v2.0.4

Laravel version

v11.0.7

Description

I'm trying to integrate Ziggy.js with Inertia.js SSR in a Svelte application, but I'm having trouble passing the Ziggy configuration to the Inertia.js context. Here's my current setup (ssr.js):

// ssr.js
import { createInertiaApp } from '@inertiajs/svelte'
import createServer from '@inertiajs/svelte/server'
import { route } from 'ziggy-js'

createServer(page => createInertiaApp({
  page,
  resolve: name => {
    const pages = import.meta.glob('./Pages/**/*.svelte', { eager: true });
    return pages[`./Pages/${name}.svelte`];
  },
  setup({ el, App, props }) {
    const Ziggy = { ...props.initialPage.props.ziggy, location: new URL(props.initialPage.props.ziggy.url) };
    return new App({ target: el, props });
  },
}));

Somewhere in my svelte app I am doing this, which works fine outside of SSR:

<Link href={route('home')}>Home</Link>

But when running ssr.js I am getting the following error:

TypeError: Cannot read properties of undefined (reading 'home')
at new n (file:///path/to/project/node_modules/ziggy-js/dist/index.js:1:2281)
at s (file:///path/to/project/node_modules/ziggy-js/dist/index.js:1:5088)
at file:///path/to/project/bootstrap/ssr/ssr.js:735:13

I assume that when SSR is loading it does not know what the 'route' function is. In my svelte app it's a function on the window object but this is not available on the server. How can I make it available on the server side as well?