How to get value of current page in setup method of inertiajs 3 app?

Updated: Mar 02, 2025

How to get value of current page in setup method of inertiajs 3 app?

In InertiaJS 3, the setup method is used to configure and initialize the application. It's important to note that this method is not directly related to handling the current page or URL, as it's primarily used for setup and configuration tasks.

To get the current page or URL in an InertiaJS 3 app, you can use the usePage() hook from Composition API or this.$page from Options API. These methods provide access to the current page data, including the URL, which you can use in your components or setup methods.

Here's an example of how to use the usePage() hook to get the current page data in a setup method:

import { createApp } from 'inertia.js'
import { onMounted } from 'vue'

const app = createApp({
  setup() {
    const { url } = usePage()

    onMounted(() => {
      console.log('Current page URL:', url)
    })
  }
})

app.mount('#app')

In this example, the usePage() hook is used to extract the current page URL, and the onMounted() lifecycle hook is used to log the URL to the console when the component is mounted.

If you prefer to use the Options API, you can access the current page data using this.$page in your setup method:

import { createApp } from 'inertia.js'

const app = createApp({
  setup() {
    onMounted(() => {
      console.log('Current page URL:', this.$page.props.url)
    })
  }
})

app.mount('#app')

In this example, the current page URL is accessed using this.$page.props.url in the onMounted() lifecycle hook.

Keep in mind that both methods should be used inside a component or a setup function, as they are not available at the root level of your application.