Nuxt 08 ๐ Nitro Server Engine & API Routes โ Building backend endpoints, server middleware, and utilities in server/
Nuxt is not just a Vue framework; it is a full-stack meta-framework. At its heart lies Nitro, the server engine that transforms your codebase into a universal, deployable server. Nitro is not just a “backend folder”โit is an H3-based engine that runs natively on Node.js, Deno, Bun, Cloudflare Workers, Vercel Edge, and any other environment that supports standard web APIs.
This chapter covers the architecture of the server/ directory, which transforms your file structure into API routes. It explains the H3 event handler pattern, the difference between api/ and routes/ folders, how server middleware intercepts requests, and how to use server utilities to keep your backend code clean. We will also look at the server/plugins lifecycle hooks and the shared utility system that auto-imports your logic across the entire server layer.
Key point: Nitro treats your server/ directory as a file-system router; every file inside server/api is automatically prefixed with /api and exposed as an endpoint, while the engine itself uses a standard H3 event handler to manage the request and response lifecycle, making your backend code portable across any cloud provider.
Why Nitro exists
The deployment fragmentation problem. Historically, writing a Node.js backend meant locking yourself into a Node runtime. Deploying that to a Serverless function (AWS Lambda, Vercel) or an Edge Worker (Cloudflare) required different adapters and APIs. Nitro solves this by abstracting the server layer, outputting a generic server build that works on any platform, while polyfilling platform-specific features to look like standard Web APIs.
The “Cold Start” problem. Traditional server frameworks load the entire application, all dependencies, and all routes at startup. Nitro uses code-splitting and an optimized entry point that only loads the code required for the specific route being hit. This massively reduces bundle size and startup time, which is critical for serverless functions where you are billed by execution time.
The routing overhead problem. In express-like frameworks, you manually define route-to-handler mappings (app.get('/users', ...)). As the app grows, this file becomes a bottleneck. Nitro uses file-system routing: server/api/users/[id].get.ts is the route. This pattern matches the rest of Nuxt, making the backend mental model identical to the frontend pages directory.
The middleware complexity problem. Global request interceptors, logging, session validation, and header manipulation often become tangled messes of nested app.use() calls. Nitro provides a clean, folder-based structure: server/middleware files run automatically on every request, in order, without requiring manual registration or complex configuration.
The shared logic problem. Backend code is often repeated across handlers (database connections, validation, error formatting). Nitroโs server/utils directory provides auto-imported helper functions that are available in every API route and middleware file, ensuring consistency without explicit import statements.
a. The Nitro File-System (Routing)
Nitro routes are determined by the folder structure inside the server/ directory. There are three primary folders, and the naming convention determines the URL path and the HTTP method.
// server/api/hello.ts
export default defineEventHandler((event) => {
return { message: "Hello API" };
});
// Exposed as: GET /api/hello
server/api/ is the standard location for API endpoints. Files here are automatically prefixed with /api. server/routes/ is for non-prefixed routes. If you place a file in server/routes/users.ts, it is exposed as /users, not /api/users. This is useful for creating webhooks, RSS feeds, or custom server-side pages.
Dynamic routes use the bracket syntax: server/api/users/[id].ts. The event object allows you to access these parameters easily.
// server/api/users/[id].ts
export default defineEventHandler((event) => {
const id = getRouterParam(event, "id"); // Access dynamic segment
return { userId: id };
});
You can also restrict methods by suffixing the filename. server/api/login.post.ts only responds to POST requests. If a GET request hits that route, Nitro automatically returns a 405 Method Not Allowed error.
b. Request Handling (Events & Utilities)
Every handler in Nitro is an “event handler.” It receives an event object, which is an abstraction over the native Node req and res objects (or their equivalents on edge runtimes). You must return the value, and Nitro serializes it as JSON by default.
// server/api/submit.post.ts
export default defineEventHandler(async (event) => {
// Parsing the request body
const body = await readBody(event);
// Parsing query parameters (?page=1)
const query = getQuery(event);
// Accessing headers
const auth = getHeader(event, "Authorization");
return { success: true, received: body };
});
The event.context object is a shared container for the duration of the request. You can attach data to it in middleware and read it in the route handler.
// server/middleware/auth.ts
export default defineEventHandler((event) => {
// Attach data to the request context
event.context.user = { id: 1, role: "admin" };
});
// server/api/profile.ts
export default defineEventHandler((event) => {
return event.context.user; // Accessible here
});
Utilities like setCookie, deleteCookie, sendRedirect, and createError are auto-imported. createError is critical: it creates a standardized error object that Nuxt handles gracefully, turning it into a JSON response with the correct HTTP status code.
c. Server Middleware and Plugins
Middleware files in server/middleware/ run on every request. They are the place for logging, auth, CORS, or modifying headers. They are executed in alphabetical order based on the filename.
// server/middleware/log.ts
export default defineEventHandler((event) => {
console.log(`New request: ${getRequestURL(event)}`);
});
Server plugins, located in server/plugins/, are different. They do not run per request; they run exactly once when the Nitro server initializes (startup). Use plugins to establish database connections, initialize global stores, or register Nitro hooks.
// server/plugins/db.ts
export default defineNitroPlugin((nitroApp) => {
console.log("Nitro server initialized");
// Register a hook
nitroApp.hooks.hook("request", (event) => {
// This runs on every request, similar to middleware
});
});
The server/utils directory is the most powerful feature for code sharing. Anything exported from a .ts file in this directory is auto-imported across all your API routes and middleware. You do not need import { ... } from ....
// server/utils/db.ts
export const getUser = (id: string) => {
return db.query(`SELECT * FROM users WHERE id = ${id}`);
};
// server/api/users/[id].ts
export default defineEventHandler((event) => {
const id = getRouterParam(event, "id");
return getUser(id); // getUser is automatically available
});
Complete Example Session
// ============================================
// PART 1: THE BASIC API ENDPOINT
// ============================================
// server/api/time.get.ts
export default defineEventHandler((event) => {
return { time: new Date().toISOString() };
});
// ============================================
// PART 2: DYNAMIC ROUTE PARAMS
// ============================================
// server/api/post/[id].ts
export default defineEventHandler((event) => {
const id = getRouterParam(event, "id");
return { id };
});
// ============================================
// PART 3: POST REQUEST WITH BODY PARSING
// ============================================
// server/api/user.post.ts
export default defineEventHandler(async (event) => {
const body = await readBody(event);
if (!body.email) {
throw createError({ statusCode: 400, statusMessage: "Missing email" });
}
return { status: "created" };
});
// ============================================
// PART 4: MIDDLEWARE FOR AUTH
// ============================================
// server/middleware/auth.ts
export default defineEventHandler((event) => {
const url = getRequestURL(event);
if (url.pathname.startsWith("/api/admin")) {
const auth = getHeader(event, "Authorization");
if (!auth) throw createError({ statusCode: 401 });
event.context.authorized = true;
}
});
// ============================================
// PART 5: SERVER UTILITY (AUTO-IMPORTED)
// ============================================
// server/utils/format.ts
export const formatResponse = (data: any) => ({
data,
timestamp: Date.now(),
});
// server/api/data.ts
export default defineEventHandler((event) => {
return formatResponse({ msg: "Hello" });
});
// ============================================
// PART 6: SERVER PLUGIN (STARTUP)
// ============================================
// server/plugins/init.ts
export default defineNitroPlugin((nitroApp) => {
// Logic here runs once when the server starts
});
// ============================================
// PART 7: SETTING COOKIES
// ============================================
// server/api/cookie.ts
export default defineEventHandler((event) => {
setCookie(event, "session", "abc", { httpOnly: true });
return { ok: true };
});
// ============================================
// PART 8: QUERY PARAMETERS
// ============================================
// server/api/search.ts
export default defineEventHandler((event) => {
const query = getQuery(event);
return { search: query.q };
});
// ============================================
// PART 9: REDIRECTS
// ============================================
// server/routes/old.ts
export default defineEventHandler((event) => {
return sendRedirect(event, "/new", 301);
});
// ============================================
// PART 10: CUSTOM ERROR HANDLING
// ============================================
// server/api/error.ts
export default defineEventHandler((event) => {
throw createError({
statusCode: 418,
statusMessage: "I am a teapot"
});
});
The example session covered basic endpoints, dynamic params, body parsing, middleware, shared utils, startup plugins, cookies, query parameters, redirects, and custom error handling.
Quick Reference
Directory Structure
| Folder | Purpose | URL Path |
|---|---|---|
server/api | API Handlers | /api/... |
server/routes | Custom Routes | /... |
server/middleware | Request Interceptors | N/A (runs on all) |
server/plugins | Startup Logic | N/A |
server/utils | Shared Helpers | N/A |
Event Utilities
| Utility | Description |
|---|---|
defineEventHandler | Create a route handler |
getQuery | Parse ?foo=bar |
readBody | Parse POST/PUT body |
getHeader | Read request header |
setCookie | Set response cookie |
createError | Throw HTTP error |
Plugin & Middleware
| File | Timing | Usage |
|---|---|---|
middleware/*.ts | Every request | Auth, Logs, CORS |
plugins/*.ts | Once at startup | DB Init, Global Hooks |
utils/*.ts | On-demand | Shared Logic |
Best Practices
โ Do This:
// Namespace routes logically
// server/api/users/profile.ts // โ
// Use server utils for business logic
// server/utils/auth.ts // โ
// Use Type-safe event handlers
// defineEventHandler((event) => { ... }) // โ
// Handle errors with createError
// throw createError({ statusCode: 400 }); // โ
// Namespace your middleware files
// server/middleware/01-logger.ts // โ
โ Don’t Do This:
// Putting heavy logic in the API file
// server/api/users.ts (1000 lines of code) // โ
// Trying to import external libraries without installing
// import { something } from 'non-existent' // โ
// Blocking the event loop in handlers
// while(true) { ... } // โ
// Ignoring the event object
// const handler = () => { ... } // โ
// Using Node.js native 'http' module methods
// req.on('data', ...) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Route not found | File structure mismatch | Check server/api vs routes |
Body is undefined | Forgot await | Use await readBody(event) |
| Middleware execution order | Filenames | Use 01-, 02- prefix |
| Server code not found | Not in server/ | Move file to correct dir |
| Blocking async code | CPU intensive task | Use Worker threads |
Real-World Examples
1. Simple JSON API
export default defineEventHandler(() => ({ ok: true }));
2. Get Query Param
export default defineEventHandler((event) => getQuery(event).id);
3. Parse JSON Body
export default defineEventHandler(async (event) => await readBody(event));
4. Protect a Route
if (!event.context.user) throw createError({ statusCode: 401 });
5. Redirect
return sendRedirect(event, '/login');
6. Set Header
setHeader(event, 'Content-Type', 'application/json');
7. Set Cookie
setCookie(event, 'key', 'value');
8. Use Shared Utility
export default defineEventHandler(() => mySharedUtil());
9. Dynamic Route
getRouterParam(event, 'id');
10. Method Restriction
// server/api/submit.post.ts
Visual
Nitro File Routing
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ DIRECTORY STRUCTURE โ
โ server/ โ
โ โโโ api/ โ
โ โ โโโ users.get.ts โโโบ GET /api/users โ
โ โโโ routes/ โ
โ โ โโโ feed.xml.ts โโโบ GET /feed.xml โ
โ โโโ middleware/ โ
โ โ โโโ auth.ts โโโบ All requests โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Request Lifecycle
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ REQUEST FLOW โ
โ โ
โ Request โโโบ Middleware โโโ โ
โ โผ โ
โ Event Handler โโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ Response โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Nitro Engine
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ NITRO CORE โ
โ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โ
โ โ Node / Bun โ โ Cloudflare โ โ
โ โ Platform โ โ Workers โ โ
โ โโโโโโโโโโโฌโโโโโโโโโ โโโโโโโโโโโฌโโโโโโโโโ โ
โ โโโโโโโบ NITRO โโโโโโโโโ โ
โ โ โ
โ Universal API โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Engine | Nitro |
| Handler | H3 |
| Routing | File-system |
| Middleware | Folder-based |
| Utils | Auto-imported |
| Plugin | Startup |
Key takeaways:
- Nitro is cross-platform. It converts your code into a universal server that runs on Node, Edge, or Serverless environments with zero configuration changes.
- File-system routing is the standard.
server/apifiles are automatically prefixed with/api, whileserver/routesfiles are not, allowing you to build both APIs and static assets. - Use H3 event handlers. Every route must export a default handler using
defineEventHandler, which gives you access to the unifiedeventobject. - Middleware is structural. Place middleware in
server/middlewareand it executes on every incoming request; prefix filenames with numbers (e.g.,01-auth.ts) to control the execution order. - Shared logic goes in utils. Files in
server/utilsare automatically imported everywhere in the server layer, reducing boilerplate imports. - Plugins handle startup. Use
server/pluginsfor database connections or global initializations that only need to run once when the server boots.
Remember: Nitro is designed to make the backend feel as seamless as the Nuxt frontend. Use the file system to define your routes, rely on server/utils for shared business logic, and leverage the standardized H3 event object for all request/response operations. By adhering to the server/api, middleware, and utils directory conventions, you build a backend that is decoupled from any specific host, ensuring your Nuxt app is future-proof and deployment-agnostic.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!