Vue error handling with vue:error hook
Nuxt provides a vue:error hook that will be called if any errors propagate up to the top level during Vue rendering lifecycle. This hook is based on the onErrorCaptured lifecycle hook. You can use vueApp.config.errorHandler to provide a global error handler that receives all Vue errors.
Startup errors and app:error hook
Nuxt will call the app:error hook if there are any errors in starting your Nuxt application. This includes: running Nuxt plugins, processing app:created and app:beforeMount hooks, rendering Vue app to HTML during SSR, mounting the app on client-side (though should be handled with onErrorCaptured or vue:error), and processing the app:mounted hook.
Vue error handler plugin example
Example of setting up a global 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
})
})
```
routeRules affecting client and server behavior
Some route rules (appMiddleware, redirect, prerender) affect client-side behavior in addition to server-side rendering. The ssr, appMiddleware, and noScripts route rules are Nuxt-specific to change behavior when rendering pages to HTML.
defineEventHandler signature example
Server endpoints and middleware are created by exporting a default result from defineEventHandler. Example: `export default defineEventHandler(async (event) => { // handler logic })`
Nuxt server powered by Nitro
Nuxt's server is powered by Nitro, an open-source framework originally created for Nuxt and now part of UnJS. It can be used with other frameworks or standalone.
Nitro capabilities in Nuxt
Nitro provides full control of the server-side part of the app, universal deployment on any provider with many zero-config options, and hybrid rendering capabilities.
defineEventHandler for server endpoints and middleware
Server endpoints and middleware are defined using defineEventHandler from 'nitro/h3'. The handler is an async function that receives an event parameter and can return text, json, html, or a stream.
Nitro uses h3 framework
Nitro internally uses h3, a minimal HTTP framework built for high performance and portability.
Server endpoints hot module replacement and auto-import
Server endpoints and middleware support hot module replacement and auto-import out-of-the-box, like other parts of the Nuxt application.
Nitro deployment presets
Nitro offers more than 15 presets to build Nuxt apps for different cloud providers and servers, including Cloudflare Workers, Netlify Functions, Vercel Cloud, Deno, and Bun.
Setting response status codes
Use setResponseStatus(event, statusCode) utility to return status codes other than 200. For example, setResponseStatus(event, 202) returns 202 Accepted.
useRuntimeConfig in server routes
Use useRuntimeConfig() in server handlers to access runtime configuration. Configuration is defined in nuxt.config.ts with the runtimeConfig key and environment variables are set with NUXT_ prefix in .env files.
Parsing cookies in server routes
Use parseCookies(event) to access cookies in server handlers. This returns an object with cookie key-value pairs.
Forwarding context and headers in server routes
By default, headers from the incoming request and request context are not forwarded when making fetch requests in server routes. Use event.$fetch to forward the request context and headers when making fetch requests. Headers that are not forwarded include: transfer-encoding, connection, keep-alive, upgrade, expect, host, and accept.
event.waitUntil for background tasks
Use event.waitUntil(promise) to await a promise in the background without delaying the response to the client. This is useful for tasks like caching and logging that shouldn't block the response. The promise will be awaited before the handler terminates, ensuring the task is completed even if the server would otherwise terminate the handler right after the response is sent.
Nested router with h3
Create a nested router using createRouter from h3, define event handlers with defineEventHandler, and use useBase('/api/path', router.handler) to mount the router at a specific base path.
Sending streams in server routes
Use sendStream(event, fs.createReadStream('/path/to/file')) from h3 to send streams in server routes. This is an experimental feature available in all environments.
Sending redirects in server routes
Use sendRedirect(event, '/path/redirect/to', 302) to send a redirect response. The status code 302 is the default for redirects.
Legacy Node middleware support
Use fromNodeMiddleware to wrap legacy Node.js middleware or handlers to work with h3. For handlers: export default fromNodeMiddleware((req, res) => { res.end('Legacy handler') }). For middleware: export default fromNodeMiddleware((req, res, next) => { next() }). Legacy support is possible but advised to avoid. Never combine next() callback with a legacy middleware that is async or returns a Promise.
useStorage in server handlers
Use useStorage('redis') in server handlers to access configured storage. Methods include: getKeys() to list all keys, setItem(key, value) to set a key, and removeItem(key) to remove a key.
server/ directory purpose and scanning
The server/ directory is used to register API and server handlers with Hot Module Replacement (HMR) support. Nuxt automatically scans files inside server/api/, server/routes/, and server/middleware/ directories to register handlers.
Server handler export requirement
Each file in the server/ directory should export a default function defined with defineEventHandler() or eventHandler() (which is an alias). The handler can directly return JSON data, a Promise, or a Response object.
Do not mix Vue and Nitro code
Do not import Vue app code (components, composables, or other app-only utilities) in server routes or utilities, and do not import server-only code in the app.
API routes automatic /api prefix
Files inside server/api/ are automatically prefixed with /api in their route. A file at server/api/hello.ts becomes accessible at /api/hello.
Server routes directory
Files placed in server/routes/ directory create server routes without the /api prefix. A file at server/routes/hello.ts is accessible at /hello.
Server middleware purpose and behavior
Nuxt automatically reads files in server/middleware/ to create server middleware. Middleware handlers run on every request before any other server route to add or check headers, log requests, or extend the event's request object. Middleware handlers should not return anything, close, or respond to the request; they should only inspect or extend the request context or throw an error.
Server routes dynamic routes limitation
Server routes do not support the full functionality of dynamic routes as pages do.
Server plugins registration
Nuxt automatically reads files in server/plugins/ directory and registers them as Nitro plugins. This allows extending Nitro's runtime behavior and hooking into lifecycle events. Plugins use definePlugin() from 'nitro'.
Server utilities directory
Server routes are powered by h3js/h3 which provides a set of helpers. Additional custom helpers can be added in the server/utils/ directory.
#server alias for imports
The #server alias (available in Nuxt 4.3+) can be used to import files from anywhere within the server/ directory, regardless of the importing file's location. For example: import { formatUser } from '#server/utils/formatUser'. This alias can only be used within the server/ directory; importing from #server in client code will result in an error.
Server types auto-import
Types placed in server/types/ are auto-imported in the server context only, making them available in server routes, middleware, plugins, and utilities without importing them. Only files directly in server/types/ are scanned; files in nested subdirectories are not auto-imported. Types needed in the Vue app should belong in shared/types/ instead.
Dynamic route parameters in server routes
Server routes can use dynamic parameters within brackets in the filename like /api/hello/[name].ts. Parameters are accessed via getRouterParam(event, 'name'). For example, a file server/api/hello/[name].ts accessed at /api/hello/nuxt returns data about the 'nuxt' parameter.
HTTP method matching with file suffixes
Handler filenames can be suffixed with .get, .post, .put, .delete, etc. to match specific HTTP methods. For example, test.get.ts handles GET requests and test.post.ts handles POST requests to the same route. A GET request returns 'Test get handler', a POST request returns 'Test post handler', and any other method returns a 405 error. Use index.[method].ts inside a directory to structure code differently or create API namespaces.
Catch-all routes in server directory
A file named server/api/foo/[...].ts registers a catch-all route for all requests that do not match any route handler, such as /api/foo/bar/baz. Access the route path via event.context.path and the route segment via event.context.params._. Alternatively, use [...slug] to name the catch-all route and access it via event.context.params.slug.
Body handling in server routes
Use readBody(event) to read the request body in server handlers. This must be used in POST requests; using readBody within a GET request will throw a 405 Method Not Allowed HTTP error. Use submit.post.ts filename to match POST requests that can accept the request body.
Query parameter extraction from server routes
Use getQuery(event) to extract query parameters from a request. For example, a query /api/query?foo=bar&baz=qux is accessed via const query = getQuery(event), then query.foo and query.baz.
Error handling in server routes
If no errors are thrown, a status code of 200 OK is returned. Any uncaught errors return a 500 Internal Server Error HTTP error. To return other error codes, throw an exception using createError with status and statusText properties.