Nuxt Tip: How to Fix "Nuxt Instance Unavailable" Error
Michael Hoffmann
@mokkapps
If you are using Nuxt 3, you probably already encountered the "Nuxt Instance Unavailable" error. What is it, and how to fix it?
What is the "Nuxt Instance Unavailable" error?
You probably received this error in middleware or plugin, which includes async
/ await
code in a try/catch
block. For example:
export default defineNuxtRouteMiddleware(async (to, from) => {
let user
try {
user = await fetchUser()
} catch (error) {
user = null
}
if (!user) {
return navigateTo('/login')) // ☠️ the error happens in this line
}
})
The error happens because the compiler lost the Nuxt context in the try/catch
block. Nuxt 3 internally uses unjs/unctx to enable composables like navigateTo()
to work without directly passing nuxtApp
to them.
Unfortunately, the unjs/unctx
transformation to automatically restore context is buggy with try/catch
statements containing await
. It is a known issue in Nuxt 3.7 and will hopefully be fixed in future updates.
How to fix the error?
The solution is to use the runWithContext
method:
export default defineNuxtRouteMiddleware(async (to, from) => {
let user
try {
user = await fetchUser()
} catch (error) {
user = null
}
if (!user) {
return nuxtApp.runWithContext(() => navigateTo('/login'))
}
})
Further Reading
Check the official docs for a deeper explanation of context.
If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :