Nuxt/docs/content/3.docs/2.directory-structure/13.server.md

2.7 KiB

icon title head.title
IconDirectory server Server directory

Server directory

Nuxt uses the server/ directory to create any backend logic for your application. It supports HMR and powerful features.

The server/ directory contains API endpoints and server middleware for your project.

API Routes

Nuxt will automatically read in any files in the ~/server/api directory to create API endpoints.

Each file should export a default function that handles API requests. It can return a promise or JSON data directly (or use res.end()).

Examples

Hello world

export default (req, res) => 'Hello World'

See the result on http://localhost:3000/api/hello.

Async function

export default async (req, res) => {
  await someAsyncFunction()

  return {
    someData: true
  }
}

Example: Using Node.js style

import type { IncomingMessage, ServerResponse } from 'http'

export default async (req: IncomingMessage, res: ServerResponse) => {
  res.statusCode = 200
  res.end('Works!')
}

Accessing req data

import { useBody, useCookies, useQuery } from 'h3'

export default async (req, res) => {
  const query = useQuery(req)
  const body = await useBody(req) // only for POST request
  const cookies = useCookies(req)
  
  return { query, body, cookies }
}

Learn more about h3 methods.

Server Middleware

Nuxt will automatically read in any files in the ~/server/middleware to create server middleware for your project.

These files will be run on every request, unlike API routes that are mapped to their own routes. This is typically so you can add a common header to all responses, log responses or modify the incoming request object for later use in the request chain.

Each file should export a default function that will handle a request.

export default async (req, res) => {
  req.someValue = true
}

There is nothing different about the req/res objects, so typing them is straightforward.

import type { IncomingMessage, ServerResponse } from 'http'

export default async (req: IncomingMessage, res: ServerResponse) => {
  req.someValue = true
}

To pass the request deeper into the application, you can return inside the function:

export default async (req, res) => {
  const isNotHandledByThisMiddleware = req.url.includes('/some-unhandled-url-path/')
  if(isNotHandledByThisMiddleware) {
    return
  }

  // Actual logic here
}

::alert{type=info icon=🔎} Find more information about custom middleware in the documentation for nuxt.config.js ::