Server APIs & Middleware
Relevant source files
The following files were used as context for generating this wiki page:
Nuxt provides a robust framework for building full-stack applications by leveraging a dedicated server/ directory for APIs, middleware, and server-side plugins. This system is powered by Nitro, which allows for the creation of type-safe endpoints and the execution of logic before reaching the client-side application. The server infrastructure supports various rendering modes, including SSR, SPA, and hybrid rendering, by managing route rules and server-side execution contexts.
Sources: README.md, packages/schema/src/types/schema.ts:503-509
Server Architecture and Lifecycle
The Nuxt server architecture relies on the resolution of templates and the generation of virtual files (VFS) to bridge the gap between user-defined code and the runtime environment. The core application logic resolves middleware, plugins, and app configurations from various layers (base and extended) to build a unified server-side entry point.
Template Generation Flow
The server environment is constructed through a series of template compilations. Nuxt generates specialized files for both client and server contexts, ensuring that environment-specific dependencies (like Nitro runtime config) are correctly injected.
The resolveApp function scans for layouts, middleware, plugins, and app.config files across all project layers to populate the NuxtApp object.
Sources: packages/nuxt/src/core/app.ts:47-152, packages/nuxt/src/core/templates.ts:400-450
Server Middleware
Server middleware in Nuxt allows for global or route-specific logic execution. Unlike client-side middleware which runs during navigation, server middleware is processed by the Nitro engine during the HTTP request lifecycle.
Middleware Types and Registration
Middleware is automatically registered from the middleware/ directory. Nuxt distinguishes between global middleware (applied to every request) and named middleware (applied via page metadata).
| Property | Description | Source |
|---|---|---|
name | The unique identifier of the middleware. | packages/nuxt/src/core/app.ts:182 |
path | The file path to the middleware implementation. | packages/nuxt/src/core/app.ts:182 |
global | Boolean indicating if it runs on every route. Identified by .global suffix. | packages/nuxt/src/core/app.ts:182 |
In the generated middleware.mjs, global middleware is imported statically, while named middleware is wrapped in defineAsyncComponent or dynamic imports for lazy loading.
Sources: packages/nuxt/src/core/templates.ts:452-491, packages/nuxt/src/core/app.ts:173-186
Server Middleware Execution
Server APIs
The server/api directory is the primary location for defining server-side endpoints. These handlers are automatically scanned and served by the Nitro engine.
Data Fetching and Serialization
Nuxt's $fetch utility is patched on the server to route internal requests directly through Nitro, bypassing the external network stack. This preserves global fetch compatibility while optimizing performance. Server APIs automatically handle serialization, allowing developers to return objects, strings, or numbers directly.
| Feature | Behavior | Source |
|---|---|---|
| Native Fetch | Preserves global fetch while internal $fetch is optimized for Nitro. | test/basic.test.ts:46-51 |
| State Preservation | Server state can be maintained across requests (e.g., counters). | test/basic.test.ts:53-58 |
| Auto-imports | Utils and composables from the server directory are auto-imported. | test/basic.test.ts:60-68 |
Sources: test/basic.test.ts:39-68, packages/nuxt/src/core/templates.ts:566-578
Route Rules and Hybrid Rendering
Nuxt allows fine-grained control over server behavior through routeRules. This configuration enables hybrid rendering strategies (SSR, SPA, ISR, SWR) on a per-route basis.
Configuration Schema
Route rules are defined in nuxt.config.ts or inline using defineRouteRules (when enabled). These rules are compiled into a router that Nitro uses to decide how to serve each path.
| Rule | Description | Source |
|---|---|---|
ssr | Enables or disables Server-Side Rendering. | packages/schema/src/types/schema.ts:685-688 |
prerender | Hints the server to generate the page at build time. | packages/nuxt/src/pages/module.ts:665-680 |
redirect | Configures server-side HTTP redirects. | packages/nuxt/src/pages/module.ts:738-752 |
noScripts | Disables rendering of Nuxt scripts and JS resource hints. | packages/schema/src/types/schema.ts:628-633 |
Sources: packages/schema/src/types/schema.ts:983-990, packages/nuxt/src/pages/module.ts:60-80
Inline Route Rules Resolution
When experimental.inlineRouteRules is enabled, Nuxt scans page files for the defineRouteRules macro. These rules are then aggregated and passed to Nitro to update its configuration dynamically.
Sources: packages/nuxt/src/pages/module.ts:74-84, packages/nuxt/src/pages/module.ts:119-122
Server Plugins
Server plugins allow for the execution of logic during the Nuxt server initialization phase. These are distinct from client-side plugins and are typically used for initializing server-side libraries, modifying the nuxtApp context on the server, or injecting server-only utilities.
Nuxt generates a specific plugins.server.mjs file that filters and sorts plugins based on their mode ('server' or 'all') and their dependencies (dependsOn).
Sources: packages/nuxt/src/core/templates.ts:114-131, packages/nuxt/src/core/app.ts:193-207
Dependency Resolution
Plugins are sorted using a dependency graph to ensure that if a plugin depends on another, it is initialized later in the lifecycle.
Error Handling
Server-side errors are captured and rendered via the errorComponent. Nuxt differentiates between JSON and HTML error responses based on the Accept header.
- JSON Errors: Return structured data including
message,status, andstatusText. - HTML Errors: Render the configured error page (defaulting to
nuxt-error-page.vueif not provided).
Sources: test/basic.test.ts:546-565, packages/nuxt/src/core/app.ts:99-100
Summary
The Server APIs and Middleware system in Nuxt provides a high-performance environment for server-side logic. By integrating Nitro, Nuxt automates the scanning, registration, and optimization of server handlers. Through the use of route rules and specialized server templates, the framework supports complex hybrid rendering needs while maintaining a type-safe bridge between the server and client contexts.