new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Nuxt · Getting started · all subjects

error-handling

74 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

Node 16 cookie behavior with error page

If running on Node 16 and setting cookies when rendering an error page, they will overwrite cookies previously set. It is recommended to use a newer version of Node as Node 16 reached end-of-life in September 2023.

Sources of unpreventable user runtime errors in Nuxt

Nuxt can encounter several categories of unpreventable user runtime errors: errors during the Vue rendering lifecycle (SSR and CSR), server and client startup errors, errors during Nitro server lifecycle in the server/ directory, and errors downloading JS chunks.

Vue error handling with onErrorCaptured

You can hook into Vue errors using the onErrorCaptured lifecycle hook from Vue's Composition API.

vue:error hook for top-level Vue errors

Nuxt provides a vue:error hook that will be called if any errors propagate up to the top level of the Vue application.

Global Vue error handler with vueApp.config.errorHandler

You can provide a global error handler through vueApp.config.errorHandler, which will receive all Vue errors, even if they are handled by other error handling mechanisms.

Vue error handler plugin example

Example of setting up a global Vue error handler in a Nuxt plugin: ```ts export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.config.errorHandler = (error, instance, info) => { // handle error, e.g. report to a service } // Also possible nuxtApp.hook('vue:error', (error, instance, info) => { // handle error, e.g. report to a service }) }) ```

app:error hook for startup errors

Nuxt will call the app:error hook if there are any errors during startup of your Nuxt application. This includes errors running Nuxt plugins, processing app:created and app:beforeMount hooks, rendering Vue app to HTML during SSR, mounting the app on client-side, and processing the app:mounted hook.

Chunk loading error handling behavior

Nuxt provides built-in support for handling chunk loading errors caused by network connectivity failure or new deployment. By default, Nuxt performs a hard reload when a chunk fails to load during route navigation. You can disable this with experimental.emitRouteChunkError set to false, or set it to manual if you want to handle errors yourself.

Fatal error response behavior

When Nuxt encounters a fatal error (any unhandled error on the server, or an error created with fatal: true on the client), it will either render a JSON response if requested with Accept: application/json header, or trigger a full-screen error page.

When error pages render on server side

An error page may render during the server lifecycle when: processing Nuxt plugins, rendering Vue app into HTML, or when a server API route throws an error.

When error pages render on client side

An error page may render on client side when: processing Nuxt plugins, before mounting the application (app:beforeMount hook), mounting the app if the error was not handled with onErrorCaptured or vue:error hook, or when the Vue app is initialized and mounted in browser (app:mounted).

Create custom error page with error.vue

Customize the default error page by creating an error.vue file in the source directory of your application, alongside app.vue.

error.vue component example

Example custom error page component: ```vue <script setup lang="ts"> import type { NuxtError } from '#app' const props = defineProps({ error: Object as () => NuxtError, }) const handleError = () => clearError({ redirect: '/' }) </script> <template> <div> <h2>{{ error?.status }}</h2> <button @click="handleError"> Clear errors </button> </div> </template> ```

useError composable signature

useError is a composable function with signature: function useError(): Ref<Error | { url, status, statusText, message, description, data }>. It returns the global Nuxt error that is being handled.

createError function signature and behavior

createError has signature: function createError(err: string | { cause, data, message, name, stack, status, statusText, fatal }): Error. It creates an error object with additional metadata and can be passed a string to set as error message or an object containing error properties. On server-side, it triggers a full-screen error page which can be cleared with clearError. On client-side, it throws a non-fatal error; to trigger a full-screen error page set fatal: true. In development, error cause is preserved and exposed to error page; in production, causes are never included.

statusText property requirements for createError

The statusText property in createError is intended for short, HTTP-compliant status texts (e.g., 'Not Found') and should only contain horizontal tabs, spaces, and visible ASCII characters (matching [\t\u0020-\u007E]). For detailed descriptions, multi-line messages, or content with non-ASCII characters, use the message property instead.

createError example in page

Example of using createError in a page to throw a 404 error: ```vue <script setup lang="ts"> const route = useRoute() const { data } = await useFetch(`/api/movies/${route.params.slug}`) if (!data.value) { throw createError({ status: 404, statusText: 'Page Not Found', }) } </script> ```

showError function signature

showError has signature: function showError(err: string | Error | { status, statusText }): Error. You can call this function at any point on client-side, or on server side directly within middleware, plugins or setup() functions. It will trigger a full-screen error page which can be cleared with clearError. It is recommended to use throw createError() instead.

clearError function signature

clearError has signature: function clearError(options?: { redirect?: string }): Promise<void>. This function will clear the currently handled Nuxt error and takes an optional path to redirect to, for example to navigate to a safe page.

NuxtErrorBoundary component for client-side errors

Nuxt provides a NuxtErrorBoundary component that allows you to handle client-side errors within your app without replacing your entire site with an error page. It prevents errors that occur within its default slot from bubbling up to the top level and renders the #error slot instead. The #error slot receives error as a prop, and if you set error = null it will trigger re-rendering the default slot.

NuxtErrorBoundary example

Example of using NuxtErrorBoundary to handle errors locally: ```vue <template> <!-- some content --> <NuxtErrorBoundary @error="someErrorLogger"> <!-- You use the default slot to render your content --> <template #error="{ error, clearError }"> You can display the error locally here: {{ error }} <button @click="clearError"> This will clear the error. </button> </template> </NuxtErrorBoundary> </template> ```

NuxtErrorBoundary error clearing behavior

When you navigate to another route, the error in NuxtErrorBoundary will be cleared automatically.

Important: Nuxt plugins dependencies in error handlers

Make sure to check before using anything dependent on Nuxt plugins, such as $route or useRouter, when handling errors. If a plugin threw an error, it won't be re-run until you clear the error.

Error page rendering runs middleware again

Rendering an error page is an entirely separate page load, meaning any registered middleware will run again. You can use useError in middleware to check if an error is being handled.

Error layout moved from _error.vue to error.vue

In Nuxt 3, move ~/layouts/_error.vue to ~/error.vue. If you want to ensure that this page uses a layout, you can use <NuxtLayout name="default"> directly within error.vue.

NUXT_B5001: Missing compatibilityDate

The error NUXT_B5001 occurs when no compatibilityDate is set in the Nuxt configuration. Nuxt uses this date to decide which behaviour defaults to apply, ensuring your project stays stable across Nuxt and Nitro updates instead of silently picking up new defaults.

B5003 resolution: move custom keys from runtimeConfig.app

To resolve the B5003 error, move custom keys either to runtimeConfig.public (which is exposed to the client) or to a top-level custom namespace (server-only). For example, instead of runtimeConfig.app.myKey, use runtimeConfig.public.myKey.

Error B5003: Reserved runtimeConfig.app namespace

The B5003 error occurs when custom keys are defined under runtimeConfig.app, which is a namespace reserved by Nuxt for internal values such as baseURL and cdnURL. Custom keys in this namespace can collide with Nuxt's own configuration.

B5003 resolution example: move to runtimeConfig.public

This example shows how to fix B5003 by moving a custom key from runtimeConfig.app to runtimeConfig.public: ```ts export default defineNuxtConfig({ runtimeConfig: { // instead of runtimeConfig.app.myKey public: { myKey: 'value', }, }, }) ```

E1001: Composable called outside Nuxt context

Error E1001 occurs when a composable that requires the Nuxt instance (such as useNuxtApp(), useRoute(), useFetch()) is called outside of a plugin, Nuxt hook, route middleware, or Vue setup() function. The most common trigger is calling such a composable inside an async callback (setTimeout, .then(), or after an await) where the context has been lost.

E1001 resolution: Call composables synchronously at top level

To resolve E1001, call the composable synchronously at the top of setup(), a plugin, or middleware, and reuse the captured result later. For server-side async work, wrap the call with nuxtApp.runWithContext().

B5004 error: external config file not supported

Nuxt throws error B5004 when it finds a standalone vite.config, webpack.config, nitro.config, or postcss.config file next to nuxt.config. Nuxt manages the bundler internally and ignores these external files, which are usually leftovers from migration or copied non-Nuxt projects.

B5004 example: migrate Vite config to nuxt.config

export default defineNuxtConfig({ vite: { // your Vite config here }, })

B5004 resolution: migrate config to nuxt.config

To fix B5004, move the configuration from external config files into nuxt.config under the matching key, then delete the external file. Use the 'vite' key for vite.config, 'webpack' key for webpack.config, 'nitro' key for nitro.config, and 'postcss' key for postcss.config.

Fix E1006: add library to build.transpile

To resolve E1006, add the offending library to the build.transpile configuration in nuxt.config.ts so the build pipeline can process its onPrehydrate() call.

E1006: onPrehydrate not processed by build pipeline

The E1006 error occurs when onPrehydrate() runs without being transformed by the Nuxt build pipeline. onPrehydrate() requires compile-time processing and only works on the server. This error happens when onPrehydrate() is called from a dependency that Nuxt does not transpile.

E2001: navigateTo requires external: true for external URLs

The error E2001 is raised when navigateTo() receives an external URL but the { external: true } option is not provided. Nuxt requires explicit opt-in for external navigation to avoid accidentally redirecting users away from the app. To fix this error, pass { external: true } as the second argument to navigateTo(). Example: navigateTo('https://example.com', { external: true })

E2002: Navigation with dangerous protocol

The navigateTo() function was given a URL using a dangerous protocol such as javascript:, data:, or vbscript:. Nuxt blocks these protocols to prevent XSS attacks. This error almost always indicates that unsanitized user input reached navigateTo().

E2002 resolution: validate and sanitize URLs

To fix the E2002 error, validate and sanitize user-provided URLs before passing them to navigateTo(). Only allow http:, https:, or relative paths.

E1007 resolution: Call macros only at page top level

To fix error E1007, call the macro only at the top level of a page component's <script setup>. The macro cannot be used inside composables, conditionals, or non-page components.

E1007: Compiler-hint helper called at runtime

Error E1007 occurs when a compile-time macro such as definePageMeta() is executed at runtime. These helpers are transformed away by the Nuxt build and must never run dynamically. Usually this means the macro was called inside a composable or a non-page component instead of directly in a page.

E2003: abortNavigation() called outside middleware

The error E2003 occurs when abortNavigation() is called outside a route middleware. This function can only cancel navigation from within a middleware handler. Calling it from a component, plugin, composable, or a callback that lost the middleware context will fail.

Fix E2003: move abortNavigation() into middleware

To resolve E2003, move the abortNavigation() call into the body of a defineNuxtRouteMiddleware() handler.

E2004 unknown route middleware error

Error E2004 occurs when a route middleware is referenced (usually via definePageMeta({ middleware: [...] })) but no middleware with that name exists. Common causes include a typo in the middleware name, or a middleware file that was renamed or deleted without updating its references.

E2004 resolution: middleware file naming

To fix E2004, ensure the middleware name matches a file in the middleware/ directory. Middleware names are derived from the filename: a file named middleware/auth.ts is referenced as 'auth'.

E2007 resolution: how to set page layout correctly

To fix the E2007 error, set the layout either from route middleware or statically using definePageMeta({ layout: '...' }). Do not call setPageLayout() from a component's setup() function during SSR.

E2007 error: setPageLayout called on server within component

The E2007 error occurs when setPageLayout() is called from a component's setup() function during server-side rendering (SSR). On the server, the layout must be decided before the component renders. Calling setPageLayout() during SSR produces incorrect SSR output.

E2005 resolution: use to and from arguments in middleware

To fix E2005, use the to and from routes that are passed as arguments to the middleware function instead of calling useRoute(). The middleware receives these route objects directly: export default defineNuxtRouteMiddleware((to, from) => { // use `to` / `from` instead of useRoute() })

E2005: useRoute called within middleware

The error E2005 occurs when useRoute() is called inside a route middleware, either directly or via another composable. At that point the target route is not yet resolved, so useRoute() can return unexpected values.

NUXT_E3001 resolution: use absolute or relative URLs

To resolve NUXT_E3001, use an absolute URL with an explicit protocol like https://api.example.com/data, or a relative path like /api/data. Do not use protocol-relative URLs that start with //.

NUXT_E3001 error: useFetch URL starts with //

The NUXT_E3001 error occurs when the URL passed to useFetch() starts with //. Protocol-relative URLs like this resolve to an external host, which is almost never intended and is rejected to avoid leaking requests to a different origin.

E3008 error: useAsyncData key validation

Error E3008 is raised when useAsyncData() is called without a valid key. The error message is 'useAsyncData key must be a non-empty string.' This indicates the first argument to useAsyncData() was either missing, empty, or not a string.

E3009: useAsyncData handler must be a function

useAsyncData() must be called with a handler function as its second argument. The handler is the function that performs the fetch and returns the data, so it cannot be omitted or of another type.

E4012 error: failed to parse island response

The NUXT_E4012 error occurs when Nuxt cannot parse the response returned when rendering a server component (island). This usually means the server component endpoint returned something other than the expected island payload, such as an error page or malformed HTML.

E4012 resolution: debug island endpoint response

To resolve E4012, check the server component for errors that would prevent it from rendering, confirm the island endpoint returns a valid response, and inspect the network response for the island request to see what the server actually returned.

NUXT_E5001 error: app manifest not enabled

The error NUXT_E5001 occurs when code that relies on the app manifest runs while `experimental.appManifest` is disabled. The manifest powers features such as route rules matching and prerendered-payload detection on the client, so it must be enabled for these features to work.

E4016 error cause: parent page missing NuxtPage component

The E4016 error occurs when a nested page route matches but its parent page component does not render <NuxtPage />. Vue Router requires the parent to have a <NuxtPage /> outlet to display child pages; without it, the child page is never shown.

NUXT_E6001 resolution: call head composables in valid contexts

To fix E6001, call head composables synchronously inside a component setup(), a Nuxt plugin, or route middleware. If head composables are needed after an await, capture the Nuxt context first using useNuxtApp() and then call the head composable inside nuxtApp.runWithContext().

NUXT_E6001 example: calling useHead after async work

When you need to call useHead() after an async operation, use this pattern: const nuxtApp = useNuxtApp(); await someAsyncWork(); nuxtApp.runWithContext(() => useHead({ title: 'Late title' })). This preserves the Nuxt context by capturing it before the async work and running the head composable within that context.

NUXT_E6001: Missing Unhead instance

Error E6001 occurs when a head composable such as useHead() is called without an active Unhead instance. This happens when code runs outside a valid Nuxt context, for example in a detached async callback after the Nuxt instance is no longer available.

Give your agent this brain