Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 32 ยท Server and API

Server middleware, plugins and utils

Share code and behavior across Nuxt server routes with server/middleware, server/utils, Nitro plugins and hooks, CORS, cached handlers and the storage layer.

Once you have more than a few server routes, the same chores keep coming back: reading the session, logging, adding CORS headers, caching an expensive answer, or finding a user by id. Copying that code into every handler is how bugs spread. Nitro gives each chore a home: middleware for work before every request, utils for shared functions, plugins for hooks into the server's life cycle, and a cache and storage layer for saved results.

This lesson covers all four. As before, Nuxt code is read-only because the framework cannot run here, and two Node stand-ins run live: a request pipeline with a plugin and middleware, and a cached handler with a fake clock. They model the behavior; they are not Nitro itself. You should already know how handlers work from Server routes and the Nitro engine.

Four homes for server code

Middleware Runs before every route.
Utils Shared functions, auto-imported.
Plugins Hook into the server life cycle.
Cache and storage Keep answers and data between requests.
1 / 2

Server middleware

Every file in server/middleware/ runs on every request, before the route handler, including requests for pages and not only for /api routes. Use it for things that apply broadly: attaching the signed-in user, logging, redirecting old URLs, blocking bad requests.

TypeScript
// server/middleware/02.session.ts (read-only)
export default defineEventHandler(async (event) => {
  const id = getCookie(event, 'session');
  if (id) {
    event.context.user = await findUserBySession(id);
  }
  // no return: the request continues to the next middleware or the route
});

There is one rule that surprises beginners: a middleware must not return a value. If it returns something, Nitro treats that as the response and stops. That is useful when you want it, for example to block a request, but a stray return is a classic bug. To pass information on, write to event.context, as above, and read it in the handler.

Files run in alphabetical order, so teams prefix names with numbers (01.timing.ts, 02.session.ts) when order matters. Because middleware runs for every request, keep it fast and check event.path at the top when the work only matters for some URLs:

TypeScript
export default defineEventHandler((event) => {
  if (!event.path.startsWith('/api/admin')) {
    return; // skip: not an admin route
  }
  if (!event.context.user?.isAdmin) {
    throw createError({ statusCode: 403, statusMessage: 'Admins only' });
  }
});

Throwing is the normal way to stop a request from middleware: it becomes an error response with that status code. Route middleware for pages, a different feature that runs in the Vue router, is covered in Navigation and route middleware.

Shared helpers in server/utils

Functions in server/utils/ are auto-imported into your server code, the same way composables are auto-imported on the page side (see Auto-imports). Put anything several routes need there:

TypeScript
// server/utils/auth.ts (read-only)
export function requireUser(event: H3Event) {
  const user = event.context.user;
  if (!user) {
    throw createError({ statusCode: 401, statusMessage: 'Sign in first' });
  }
  return user;
}
TypeScript
// server/api/me.get.ts (read-only): no import needed
export default defineEventHandler((event) => {
  return { name: requireUser(event).name };
});

Auto-import scans files directly inside server/utils/. If you keep helpers in subfolders, re-export them from a top-level file or import them explicitly. Server utils are not visible to your Vue components: the page bundle and the server bundle are separate, which is a feature, because it keeps database code out of the browser.

Good candidates for utils: authentication checks, database helpers, response formatters, input validators. They keep route files short enough to read at a glance, and a plain function is easy to unit test.

Nitro plugins and hooks

A Nitro plugin is a file in server/plugins/ that runs once when the server starts. It receives the Nitro app and can register hooks: functions that run at defined moments of every request.

TypeScript
// server/plugins/logger.ts (read-only)
export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook('request', (event) => {
    console.log(`${event.method} ${event.path}`);
  });

  nitroApp.hooks.hook('afterResponse', (event) => {
    console.log('finished', event.path);
  });

  nitroApp.hooks.hook('error', (error, { event }) => {
    reportToMonitoring(error, event?.path);
  });
});

The hooks you use most are request (a request arrived), beforeResponse and afterResponse (around sending the response) and error (something threw). Plugins are the right place for startup work too: opening a connection, warming a cache, or registering a global error reporter. The exact hook list and argument shapes can change between Nitro versions, so check the documentation of the version you use.

Choose between them like this: middleware to change what happens to a request, a plugin hook to observe it, and a plugin body to do something once at startup.

The pipeline, as a stand-in

The stand-in below wires these pieces into one flow: plugin hooks around everything, two middleware that run in file-name order and only prepare the event, and routes that use a shared requireUser util. Three requests show the three outcomes: public, rejected, and signed in.

Node.js Plugin hooks, middleware and a util

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The output shows [hook:request] and [hook:afterResponse] lines around each request. The second request prints [hook:error] Sign in first and ends with 401, because the session middleware found no cookie and requireUser threw. The third sends session=abc, so the middleware stored a user in event.context and the route answers 200 {"user":"Ada"}.

CORS

Browsers block a page on one origin from reading responses from another unless the server allows it with CORS headers. Most Nuxt apps call their own server and need none. If another site or a mobile app must call your API, you have two options. The simple one is a route rule in nuxt.config.ts:

TypeScript
// nuxt.config.ts (read-only)
export default defineNuxtConfig({
  routeRules: {
    '/api/public/**': { cors: true },
  },
});

For finer control, call h3's handleCors in a middleware or a handler and give it the allowed origins and methods. Never answer * for routes that use cookies or return private data; list the exact origins you trust.

Caching with defineCachedEventHandler

Some answers are expensive to build and do not change every second: a report, a sitemap, a proxied third-party API. Wrap the handler in defineCachedEventHandler and Nitro stores the response and reuses it:

TypeScript
// server/api/report.get.ts (read-only)
export default defineCachedEventHandler(
  async (event) => {
    const { team } = getQuery(event);
    return await buildReport(String(team)); // slow
  },
  {
    maxAge: 60,                              // fresh for 60 seconds
    swr: true,                               // then serve stale while refreshing
    getKey: (event) => `report:${getQuery(event).team}`,
  },
);

maxAge is how many seconds an entry counts as fresh. With swr (stale-while-revalidate), a visitor who arrives after the entry expired still gets the old answer instantly while Nitro rebuilds it in the background, so nobody waits. The cache key decides what counts as "the same request": by default it is built from the path and query, and you can customize it as above. Be careful with anything user-specific: a cached response is shared, so never cache a handler whose answer depends on the signed-in user unless the key includes that user.

Two related tools exist: defineCachedFunction caches any async function rather than a whole response, and routeRules can apply caching to a path pattern without touching the handler (see Rendering modes).

The storage layer

Under the cache sits Nitro's storage layer, built on the unstorage library: a key-value API with swappable drivers. You reach it with useStorage():

TypeScript
// server/api/visits.post.ts (read-only)
export default defineEventHandler(async () => {
  const storage = useStorage('data');
  const visits = ((await storage.getItem<number>('visits')) ?? 0) + 1;
  await storage.setItem('visits', visits);
  return { visits };
});

By default the data lives in memory and disappears when the server restarts. In nuxt.config.ts you map a name such as data to a real driver (the file system, Redis, a Cloudflare KV namespace and others) under the nitro.storage option. The code in your handlers does not change when the driver does. That makes storage a good fit for caches, flags and small records, and a poor fit for relational data, which belongs in a database (Databases and ORMs).

The cache as a stand-in

This stand-in rebuilds the cache behavior with a fake clock in seconds, so the output never varies. A Map plays the storage, and defineCached mimics maxAge and swr.

Node.js maxAge and stale-while-revalidate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the five lines. At t=0 the report is computed. At t=10 the same team is answered from the cache. A different team (blue) has its own key, so it is computed. At t=90 the red entry is older than 60 seconds, so the visitor still receives the stale report #1 while the entry is refreshed; at t=95 the refreshed report #3 is served fresh. The real Nitro refreshes in the background instead of awaiting, so the visitor never waits at all.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens if a file in server/middleware returns a value?

    Returning a value from middleware ends the request with that response. To pass data on, write to event.context and return nothing.
  2. 2. Where do you put a function such as requireUser so every server route can use it without importing?

    Files in server/utils are auto-imported into server code. app/composables is for the page side, and server/routes would turn the file into a URL.
  3. 3. What does swr: true do in defineCachedEventHandler?

    Stale-while-revalidate answers with the old value right away and refreshes the entry, so visitors do not wait for the slow work.
  4. 4. Which tool is the right place to run code once when the server starts and to observe every request?

    A file in server/plugins runs at startup and can register hooks such as request, afterResponse and error.
  5. 5. Why is caching a handler that returns the signed-in user's data risky?

    A cache entry is served to everyone who matches its key. Unless the key includes the user, one person's private answer can reach another.

Summary

  • server/middleware runs before every request in file-name order; it returns nothing and shares data through event.context.
  • server/utils holds auto-imported shared functions for server code only.
  • server/plugins run once at startup and register hooks such as request, afterResponse and error.
  • Use routeRules or handleCors for CORS, and list trusted origins.
  • defineCachedEventHandler caches responses with maxAge, swr and a custom key; never cache per-user data under a shared key.
  • useStorage() is a key-value layer with swappable drivers, in memory by default.

Next, learn how to supply secrets and settings safely in Runtime config and environment variables.