prepare:types hook for granular type control
The 'prepare:types' hook allows you to register a callback that will inject your types with granular control. Use it to push type references for the app context. The hook provides a references object that you can push paths into.
prepare:types hook with context references
The 'prepare:types' hook provides three types of references for extending TypeScript: references (app context), sharedReferences (shared context), and nodeReferences (node context). You can push paths to any or all of these to extend their type contexts accordingly.
nitro:prepare:types hook for server context
The 'nitro:prepare:types' hook allows you to extend the server type context. It provides a references object to which you can push paths to add type declarations to the server context.
defineEventHandler signature
defineEventHandler is used to define server endpoints and middleware in Nuxt. It accepts an async function that receives an event object as a parameter. The handler can return text, json, html, or even a stream. It is imported from 'nuxt/server'.
Server endpoints and middleware file location
Server endpoints and middleware are defined in the server/ directory. They support hot module replacement and auto-import like other parts of the Nuxt application.
Nuxt server powered by Nitro
Nuxt's server framework is powered by Nitro, an open-source HTTP framework that was originally created for Nuxt and is now part of UnJS. Nitro can be used on its own or with other frameworks. It internally uses h3, a minimal HTTP framework built for high performance and portability.
Nitro capabilities in Nuxt
Nitro provides Nuxt with full control over the server-side part of the app, universal deployment on any provider with many zero-config options, and hybrid rendering capabilities.
Dynamic route parameters in server routes
Server routes can use dynamic parameters within brackets in the file name like /api/hello/[name].ts and be accessed via getRouterParam(event, 'name'). Example: export default defineEventHandler((event) => { const name = getRouterParam(event, 'name'); return `Hello, ${name}!` })
HTTP method matching in server routes
Handler file names can be suffixed with .get, .post, .put, .delete, etc. to match specific HTTP methods. For example, test.get.ts handles GET requests, test.post.ts handles POST requests. Any other method returns a 405 error. You can also use index.[method].ts inside a directory for structuring code and creating API namespaces.
Server directory structure and automatic scanning
Nuxt automatically scans files inside server/, server/api/, server/routes/, and server/middleware/ directories to register API and server handlers with Hot Module Replacement (HMR) support. Files in server/api/ are automatically prefixed with /api in their route. Files in server/routes/ are registered without the /api prefix. Each file should export a default function defined with defineEventHandler() or eventHandler() (alias).
Sending streams from server routes
Use sendStream(event, stream) to send stream responses from server routes. This is an experimental feature available in all environments. Example: import fs from 'node:fs'; import { sendStream } from 'h3'; export default defineEventHandler((event) => { return sendStream(event, fs.createReadStream('/path/to/file')) })
Server storage via Nitro plugins and runtime config
Create storage mount points using server plugins with runtime config. Define plugin in server/plugins/storage.ts using definePlugin to dynamically mount drivers like Redis. Configure credentials in nuxt.config runtimeConfig. Example: const driver = redisDriver({ base: 'redis', host: useRuntimeConfig().redis.host, port: useRuntimeConfig().redis.port }); storage.mount('redis', driver);
Defining server routes in Nitro
Server routes are defined by exporting a default function created with defineEventHandler() from files in the server/ directory. Files in server/api/ are prefixed with /api, files in server/routes/ have no prefix. HTTP method can be specified with suffixes like .get, .post, etc. Dynamic segments use [param] syntax and catch-all uses [...] syntax.
Catch-all routes in server
Catch-all routes using [...].ts pattern register fallback route handling for all requests that do not match any route handler. Access the route path via event.context.path and route segment via event.context.params._. Named catch-all routes using [...slug].ts are accessed via event.context.params.slug.
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. To return other error codes, throw an exception with createError({ status: 400, statusText: 'error message' }).
Nested router in server routes
Create nested routers using h3's createRouter and useBase functions. Example: const router = createRouter(); router.get('/test', defineEventHandler(() => 'Hello World')); export default useBase('/api/hello', router.handler);
defineEventHandler signature and return types
defineEventHandler is used to define server route handlers. The handler receives an event parameter and can directly return JSON data, a Promise, or a Response object. Example: export default defineEventHandler((event) => { return { hello: 'world' } })
Server middleware behavior and restrictions
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, nor close or respond to the request, and should only inspect or extend the request context or throw an error.
Server plugins with Nitro
Nuxt automatically reads files in the server/plugins directory and registers them as Nitro plugins using definePlugin, allowing extension of Nitro's runtime behavior and hooking into lifecycle events. Example: export default definePlugin((nitroApp) => { console.log('Nitro plugin', nitroApp) })