·
1 min read

Nuxt Tip: How to Fix "Nuxt Instance Unavailable" Error

Nuxt Tip: How to Fix "Nuxt Instance Unavailable" Error Image

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:

middleware/auth.global.ts
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:

middleware/auth.ts
export default defineNuxtRouteMiddleware(async (to, from) => { let user try { user = await fetchUser() } catch (error) { user = null } if (!user) { return nuxtApp.runWithContext(() => navigateTo('/login')) } })

Info

Try to create a reproduction and report it to the Nuxt team if you have to use this method in your project. This helps the framework team to solve the issue at the framework level.

Further Reading

Check the official docs for a deeper explanation of context.

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.