Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 32 ยท Server and API

Server routes and the Nitro engine

Build backend endpoints inside a Nuxt app with server/api and server/routes: defineEventHandler, query, body, params, status codes and createError.

A Nuxt app is not only pages. The same project can answer plain HTTP requests, return JSON, serve a robots.txt, or accept a form post. You write those endpoints as files in the server/ folder, and Nuxt runs them on its server engine, Nitro. There is no separate backend project to create and no router to configure.

In this lesson you will learn which folders become routes, how a handler reads the request and builds the response, and how to report errors properly. Nuxt and Nitro code is read-only here because the framework cannot run on this site. Two Node stand-ins run live: one that turns file paths into routes, and a small h3-style router that dispatches requests to handlers. They show the idea; the real Nitro router is more capable. If you have not met the folder layout yet, read Project structure first.

Files become endpoints

server/api Routes served under /api.
server/routes Routes served at the exact path.
File suffix .get.ts or .post.ts picks the method.
[id] and [...path] Dynamic and catch-all segments.
1 / 2

What Nitro and h3 are

Nitro is the server engine inside Nuxt. When you run nuxt dev it serves your pages and your server files together. When you run nuxt build it compiles everything into a self-contained .output/ folder that can run on Node.js, on a serverless platform or on an edge runtime, depending on the preset you choose (see Building and deploying).

Nitro is built on h3, a small HTTP framework. The functions you call inside handlers, such as getQuery and readBody, are h3 helpers that Nitro auto-imports into everything under server/, just like Nuxt auto-imports Vue APIs in your pages. You never write import { getQuery } from 'h3' for these, although you may if you prefer.

server/api and server/routes

Nitro scans two folders:

  • server/api/ โ€” every file becomes a route under /api.
  • server/routes/ โ€” every file becomes a route at its own path, with no prefix.
TEXT
server/
  api/
    hello.ts                  ->  /api/hello
    users/
      index.get.ts            ->  GET  /api/users
      index.post.ts           ->  POST /api/users
      [id].get.ts             ->  GET  /api/users/:id
      [id].delete.ts          ->  DELETE /api/users/:id
    files/
      [...path].ts            ->  /api/files/**  (catch-all)
  routes/
    health.ts                 ->  /health
    robots.txt.ts             ->  /robots.txt

Use server/api for endpoints your own front end calls. Use server/routes when the exact URL matters to the outside world: health checks, robots.txt, a sitemap.xml, a webhook address that a payment provider expects.

Three naming rules cover almost everything:

  1. index means "the folder itself", so users/index.get.ts answers /api/users.
  2. A method suffix (.get, .post, .put, .patch, .delete) limits the file to that HTTP method. A file with no suffix answers every method.
  3. Square brackets make a dynamic segment ([id]), and [...path] captures the rest of the URL.

The first stand-in applies those rules to a list of file names. Real Nitro supports more, such as other suffixes and a server/api/[...].ts catch-all for unknown API paths, but the core mapping is the same.

Node.js From file paths to routes

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 real run prints one line per file, such as GET /api/users/:id <- server/api/users/[id].get.ts and ALL /robots.txt <- server/routes/robots.txt.ts. Notice that robots.txt.ts is not mistaken for a method suffix, because txt is not one of the five method names.

Your first handler

A route file has one default export: the result of defineEventHandler. The function receives an event, which represents the incoming request and the outgoing response.

TypeScript
// server/api/hello.ts (read-only)
export default defineEventHandler((event) => {
  return { message: 'Hello from Nitro', time: new Date().toISOString() };
});

Whatever you return becomes the response. An object or array is sent as JSON with the right Content-Type. A string is sent as text or HTML. The handler may be async, and it may return a promise. You rarely need a res.send() call; returning the value is the normal style.

From the browser or from a page, you call it with $fetch or useFetch (see Data fetching):

TypeScript
const hello = await $fetch('/api/hello');

During server-side rendering, $fetch('/api/...') to your own app does not make a real network round trip; Nitro calls the handler directly in the same process. That makes server-rendered pages fast.

Reading the request

h3 gives you one helper per part of the request:

TypeScript
// server/api/users/[id].get.ts (read-only)
export default defineEventHandler(async (event) => {
  const id = getRouterParam(event, 'id');         // /api/users/42 -> "42"
  const { fields } = getQuery(event);              // ?fields=name
  const token = getHeader(event, 'authorization'); // a request header
  const cookie = getCookie(event, 'session');      // a cookie value
  return { id, fields, hasToken: Boolean(token), hasCookie: Boolean(cookie) };
});

For a request body, use readBody:

TypeScript
// server/api/users/index.post.ts (read-only)
export default defineEventHandler(async (event) => {
  const body = await readBody(event);
  return { received: body };
});

Remember three facts:

  • getRouterParam always returns a string (or undefined). Convert it yourself with Number(...) when you need a number.
  • getQuery returns strings, or arrays when a key repeats (?tag=a&tag=b).
  • readBody gives you untrusted input. Anyone can send anything. Validate it before use; h3 has readValidatedBody(event, validator) and getValidatedQuery(event, validator) for that, and Forms, validation and auth flows shows the pattern.

Status codes and errors

A successful handler responds with 200. To choose another code, call setResponseStatus:

TypeScript
export default defineEventHandler(async (event) => {
  const body = await readBody(event);
  const user = await createUser(body);
  setResponseStatus(event, 201); // Created
  return user;
});

To report a failure, throw an error made with createError. Nitro catches it, sets the status code and sends a JSON error body:

TypeScript
export default defineEventHandler(async (event) => {
  const id = Number(getRouterParam(event, 'id'));
  const user = await findUser(id);

  if (!user) {
    throw createError({ statusCode: 404, statusMessage: 'User not found' });
  }
  return user;
});

On the page side, useFetch and $fetch expose this as an error object whose status code is 404. Use the right code for the right problem: 400 for invalid input, 401 when not signed in, 403 when signed in but not allowed, 404 when the thing does not exist, and 500 for your own bugs. Errors you do not catch become a 500. Details of the field names (statusMessage or the newer statusText) differ between h3 versions, so check the documentation for the version in your project.

A stand-in: a mini router

The second stand-in is not Nitro. It is about forty lines of plain JavaScript that behave like a small slice of it: routes registered with a method and a pattern, an event with getQuery, getRouterParam and readBody, a createError that sets a status, and a dispatcher that turns return values and thrown errors into responses. Real Nitro uses a fast radix-tree router and a real HTTP layer, but your handler code looks the same.

Node.js A mini h3-style router

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 run prints six lines. The first request returns two users with status 200; the third returns 404 with the message User not found; the POST with a name returns 201 and the new user ({"id":4,"name":"Margaret"}); the POST with an empty body returns 400; and the unknown /api/posts returns 404 Not Found. The pattern is what matters: a handler returns data for success and throws for failure, and one central place turns both into a status code.

Server code stays on the server

Everything under server/ is bundled only into the server output. A database password, an API key or a private SDK used there never reaches the browser, as long as you do not return it in a response. That is the main reason to put such work in a server route instead of calling a third-party service from the page. Read Runtime config and environment variables for how to supply those secrets safely.

Two habits keep server routes healthy:

  • Keep handlers thin. Parse input, call a function, return the result. Put business logic in server/utils/ (the next lesson) so you can reuse and test it.
  • Never trust the client. Check the method, validate input and verify permissions in the handler, even if your own page "would never" send bad data.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which file answers only POST requests to /api/users?

    Files in server/api are served under /api, index means the folder itself, and the .post suffix limits the handler to the POST method. A file in server/routes would not get the /api prefix.
  2. 2. How does a handler send a 404 response to the client?

    Throwing an error made with createError lets Nitro set the status code and send an error body. Returning a number would just send the number as the body with status 200.
  3. 3. What does getRouterParam(event, 'id') return for /api/users/42?

    Route parameters are always strings. Convert them with Number() when you need a number.
  4. 4. Which folder would you use for an endpoint that must live at exactly /health?

    server/routes maps files to paths without the /api prefix, so server/routes/health.ts answers /health.

Summary

  • Nitro, built on h3, runs your server/ code inside Nuxt and compiles it into the .output server.
  • server/api routes live under /api; server/routes routes live at their own path.
  • File names set the route: index, .get/.post method suffixes, [id] and [...path].
  • A handler uses defineEventHandler; returned objects become JSON.
  • Read input with getQuery, getRouterParam, getHeader and readBody, and validate it.
  • Use setResponseStatus for success codes and throw createError for failures.

Next, add shared logic and cross-cutting behavior in Server middleware, plugins and utils.