How to pass data from middleware to the redirected page
I would like to pass the collected data from the API call that is middleware as "props" in the navigateTo page I redirect to so I don't have to make 2 identical queries.
statestatestatenavigateTonavigateTonavigateTohistory.stateuseStateuseAsyncDatauseFetchexport default defineNuxtRouteMiddleware((to, from) => {
const data = // ... your API call result
return navigateTo('/redirected-page', {
state: { myData: data }
})
})<script setup>
const data = ref(null)
onMounted(() => {
data.value = history.state.myData
if (!data.value) {
// Fetch data from API if it doesn't exist
}
// Clear the state after accessing it
const { myData, ...currentState } = history.state
window.history.replaceState({ ...currentState }, '')
})
</script>export default defineNuxtRouteMiddleware(async (to, from) => {
const data = await $fetch('/api/your-endpoint')
useState('myData', () => data)
return navigateTo('/redirected-page')
})<script setup>
const myData = useState('myData')
</script><script setup>
const { data } = await useAsyncData('myData', () => $fetch('/api/your-endpoint'))
</script>