Javascript is required
·
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
1export default defineNuxtRouteMiddleware(async (to, from) => {
2  let user
3
4  try {
5    user = await fetchUser()
6  } catch (error) {
7    user = null
8  }
9
10  if (!user) {
11    return navigateTo('/login')) // ☠️ the error happens in this line
12  }
13})

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
1export default defineNuxtRouteMiddleware(async (to, from) => {
2  let user
3
4  try {
5    user = await fetchUser()
6  } catch (error) {
7    user = null
8  }
9
10  if (!user) {
11    return nuxtApp.runWithContext(() => navigateTo('/login'))
12  }
13})

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.