Nuxt/docs/content/3.docs/2.directory-structure/12.server.md
2022-01-17 11:56:12 +01:00

93 lines
2.4 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
icon: IconDirectory
title: server
head.title: Server directory
---
# Server directory
The server directory is used to create any backend logic for your Nuxt 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
```js [server/api/hello.ts]
export default (req, res) => 'Hello World'
```
See the result on <http://localhost:3000/api/hello>.
#### Async function
```js [server/api/async.ts]
export default async (req, res) => {
await someAsyncFunction()
return {
someData: true
}
}
```
**Example:** Using Node.js style
```ts [server/api/node.ts]
import type { IncomingMessage, ServerResponse } from 'http'
export default async (req: IncomingMessage, res: ServerResponse) => {
res.statusCode = 200
res.end('Works!')
}
```
#### Accessing req data
```js
import { useBody, useCookies, useQuery } from 'h3'
export default async (req, res) => {
const query = await useQuery(req)
const body = await useBody(req) // only for POST request
const cookies = useCookies(req)
return { query, body, cookies }
}
```
Learn more about [h3 methods](https://www.jsdocs.io/package/h3#package-index-functions).
## 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](#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.
```js
export default async (req, res) => {
req.someValue = true
}
```
There is nothing different about the `req`/`res` objects, so typing them is straightforward.
```ts
import type { IncomingMessage, ServerResponse } from 'http'
export default async (req: IncomingMessage, res: ServerResponse) => {
req.someValue = true
}
```
More information about custom middleware can be found in the documentation for [nuxt.config.js](/docs/directory-structure/nuxt.config#servermiddleware)