#Logging server-side errors
4 messages · Page 1 of 1 (latest)
Hi @hot crane. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To handle server-side error logging in Nuxt 3 and forward these errors to a third-party service like New Relic or Rollbar, you have several options. Let me explain the best approaches:
Using Nitro Hooks
The most comprehensive way to capture server-side errors is by using Nitro hooks. You can create a server plugin that listens to the error hook:
// server/plugins/error-logger.ts
export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('error', (error, { event }) => {
// Send error to your third-party service
console.log('Server error:', error)
// yourThirdPartyService.captureException(error)
})
})
This approach will capture all errors that occur in the Nitro server, including API routes and server middleware errors. Nitro plugins are executed once when the server starts and can register hooks for various events, including errors.
Nitro App Hooks documentation shows that the error hook receives the error object and optionally the event context.
Using a Server Plugin
Another option is to create a Nuxt server plugin:
// plugins/error-handler.server.ts
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hook('app:error', (error) => {
// Send error to your third-party service
console.log('Nuxt app error on server:', error)
// yourThirdPartyService.captureException(error)
})
})
This will capture errors that occur during the Nuxt application lifecycle on the server, such as errors in plugins, hooks, or during SSR rendering.
Using Server Middleware
You can also use server middleware to catch and log errors, though this is generally less recommended for global error handling:
// server/middleware/error-logger.ts
export default defineEventHandler((event) => {
// This middleware will run on every request
// but won't catch errors unless you specifically handle them
// It's better to use the Nitro hooks approach for error handling
})
As noted in the server middleware documentation, middleware should generally not return anything or directly respond to requests, making it less ideal for error handling.
Best Practice Recommendation
The most comprehensive approach is to combine both Nitro and Nuxt hooks:
- Use a Nitro server plugin with the
errorhook to catch all server-related errors - Use a Nuxt server plugin with the
app:errorhook to catch application-specific errors
This combination will give you the most complete coverage of potential error sources in your Nuxt 3 application.