nuxt.js

Nuxt 3 - 404 Page Not Found Error and H3Error Page not found


Whenever a user visits a non existing page I get in the logs the following error which I would rather not log for every not found page.

[nuxt] error caught during app initialization H3Error: Page not found: /.git/config at createError (file:///var/www/site1/.output/server/node_modules/h3/dist/index.mjs:128:15) at file:///var/www/site1/.nuxt/dist/server/server.mjs:2154:47 at triggerAfterEach (file:///var/www/site1/.output/server/node_modules/vue-router/dist/vue-router.mjs:3306:13) at file:///var/www/site1/.output/server/node_modules/vue-router/dist/vue-router.mjs:3209:13 at processTicksAndRejections (node:internal/process/task_queues:96:5) at file:///var/www/site1/.nuxt/dist/server/server.mjs:2170:7 at createNuxtAppServer (file:///var/www/site1/.nuxt/dist/server/server.mjs:19902:7) at Object.renderToString (file:///var/www/site1/.output/server/node_modules/vue-bundle-renderer/dist/runtime.mjs:172:19) at file:///var/www/site1/node_modules/nuxt/dist/core/runtime/nitro/renderer.mjs:128:21 at file:///var/www/site1/node_modules/nitropack/dist/runtime/renderer.mjs:12:22 { statusCode: 404, fatal: false, unhandled: false, statusMessage: 'Page not found: /.git/config', __nuxt_error: true }

I tried to create a plugin in plugins folder named errorhandler.ts with this code but its not logging anything

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.config.errorHandler = (error, context) => {
    console.log(error);
    console.log(context);
  };
});

This is an example https://stackblitz.com/edit/nuxt-starter-q2rvlp?file=plugins%2Ferrorhandler.ts.

Can anyone share some thoughts about handling not found error in Nuxt 3 and even creating a custom 404 page?

Thank you in advance!!!


Solution

  • I encountered the same problem. The 404 error messages were logged even when the 404 errors were handled by an error.vue. After a lot of searching and trying, I created a little Nitro 'plugin' which marks the h3Error as handled before calling the default error handler. This works because an error is only logged if it's marked unhandled or fatal (see source code: https://github.com/nuxt/nuxt/blob/f84df08dbcab675a8419c42cc5c2a5258df37bff/packages/nuxt/src/core/runtime/nitro/error.ts#LL28C36-L28C36)

    My code in /server/plugins.error.ts:

    import type { H3Error, H3Event } from 'h3'
    
    export default defineNitroPlugin((nitroApp) => {
        const h3OnError = nitroApp.h3App.options.onError;
        nitroApp.h3App.options.onError = (error : Error, event : H3Event) => {
            let h3error : H3Error = error as H3Error;
            
            if(h3error?.statusCode === 404)
            {
                h3error.unhandled = false;
            }
    
            if(h3OnError !== undefined)
            {
                return h3OnError(error, event);
            }
            return;
        };
    })
    

    I hope this helps.