[2.x] Fix Inertia SSR usage with Ziggy route function in setup() #1069
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR fixes an error where the Ziggy
route()
helper is undefined whenroute()
is used in thesetup()
function and Inertia SSR is being used.Steps to Reproduce
php artisan jetstream:install inertia --ssr
Welcome.vue
file, for example, use the route function inside<script setup>
:{{ test }}
npx mix --mix-config=webpack.ssr.mix.js
npm run dev
node public/js/ssr.js
ReferenceError: route is not defined
Proposed Solution
Using
route()
in the setup function will work using client-side rendering by default, because the@routes
blade directive defines it globally. According to this answer, the route function should be injected when being used in a setup function. However, for the route function to be provided, the Ziggy Vue plugin must be used.To do this in
ssr.js
, we would useZiggyVue
instead of the route mixin. This would keeproute()
available in all templates, and would make it available in setup functions if we inject it:This now works under SSR, but not when the page is client-side rendered:
inject('route')
will be undefined because we aren't using theZiggyVue
plugin inapp.js
.Therefore, the route mixin also needs to be removed from
app.js
and replaced with:Ziggy
refers to the definitionconst Ziggy
by the@routes
blade directive in<head>
.Breaking Changes
It doesn't seem like these changes will break anything in new Jetstream projects, whether using Inertia SSR or not. When only using client-side rendering, the route function can still be used in templates, setup, functions, etc. without being injected. The route function only needs to be injected when it's being used in the setup function and the page is being server-side rendered.
I wish there was a more elegant solution as I don't love having to
const route = inject('route')
where route is needed in script setup/computed functions/etc, so please let me know if there are any other ideas. I'm also not sure if this problem is big enough to warrant a change but wanted to put it out there in case others are having this issue