inertia icon indicating copy to clipboard operation
inertia copied to clipboard

Return early when using `router.on()` during SSR

Open RobertBoes opened this issue 1 year ago • 0 comments

When using router.on() it is always executed, this means the following won't work during SSR:

<script setup>
import { router } from '@inertiajs/vue3'

router.on('start', (event) => {
  console.log(`Starting a visit to ${event.detail.visit.url}`)
})
</script>

Instead, we'd need to wrap this in a onMounted hook, or check if the document/window exists;

<script setup>
import { router } from '@inertiajs/vue3'
import { onMounted } from 'vue'

onMounted(() => {
  router.on('start', (event) => {
    console.log(`Starting a visit to ${event.detail.visit.url}`)
  })
})
</script>

But since router.on() is already just a wrapper for document.addEventListener() I'd expect the wrapper to take care of that for you.

A simple fix I've made here is to simply check if we're in ssr with the isServer constant, if it is we return an empty void function

RobertBoes avatar Oct 31 '23 15:10 RobertBoes