@nuxt/docs-nightly 5.0.0-29837688.ef8d0fbb → 5.0.0-29837794.25b87beb

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -145,17 +145,20 @@ If we can't tell, code will be treated as `nitro2`.
145
145
 
146
146
  ## Nitro-specific Code
147
147
 
148
- `nuxt/server` covers request and response work: handlers, errors, query and body reading, headers, cookies, redirects, route rules and runtime config. But Nitro covers a lot more, so if you need any of these areas, you might need to stay on Nitro's own imports inside a `nitro2` or `nitro3` file.
148
+ `nuxt/server` covers request and response work: handlers, errors, router params, query and body reading and validation, headers, CORS, cookies, sessions, redirects, route rules, runtime config and app config. But Nitro covers a lot more, so if you need any of these areas, you might need to stay on Nitro's own imports inside a `nitro2` or `nitro3` file.
149
149
 
150
150
  Use the specifiers of the version the file is for. A file that imports `nitro/*` is read as Nitro 3 code, so a `nitro2` file must import `h3` and `nitropack/*` instead:
151
151
 
152
152
  | Area | In a `nitro3` file | In a `nitro2` file |
153
153
  | --- | --- | --- |
154
154
  | Storage: `useStorage()` and its driver configuration | `nitro/storage` | `nitropack/runtime` |
155
- | Sessions: `useSession`, `getSession`, `updateSession`, `clearSession` | `nitro/h3` | `h3` |
156
155
  | Caching: `defineCachedHandler()`, `defineCachedFunction()` | `nitro/cache` | `nitropack/runtime` |
156
+ | Server plugins | `definePlugin()` from `nitro` | `defineNitroPlugin()` from `nitropack/runtime` |
157
+ | Runtime hooks, including `render:html` | `useNitroHooks()` from `nitro/app` | `useNitroApp().hooks` from `nitropack/runtime` |
158
+ | App-relative fetch | `serverFetch()` from `nitro` | `useNitroApp().localFetch` from `nitropack/runtime` |
159
+ | Lazy handlers: `lazyEventHandler()` | `nitro/h3` | `h3` |
157
160
 
158
- Nitro's runtime hooks (`useNitroApp().hooks`, including `render:html`) and tasks are obviously also not supported by `nuxt/server`.
161
+ Tasks are also not supported by `nuxt/server`.
159
162
 
160
163
  ::read-more{to="/docs/guide/going-further/server-imports#reaching-past-the-surface"}
161
164
  See which h3 helpers work with the portable event, and which need Nitro-specific utilities.
@@ -36,21 +36,24 @@ This code can run under `@nuxt/nitro-server` and under `@nuxt/vite-server`, and
36
36
  | `createError`, `isNuxtError` | Construct and recognise an HTTP error. |
37
37
  | `getRequestURL` | The URL of the request. |
38
38
  | `getRequestHeader`, `getRequestHeaders` | Read request headers. |
39
- | `getQuery` | Read the query string. |
40
- | `readBody` | Read and parse the request body. |
39
+ | `getRouterParam`, `getRouterParams` | Read the dynamic segments matched for the request. |
40
+ | `getRequestIP` | The client IP address, with [forwarded headers trusted on request](#client-ip). |
41
+ | `getQuery`, `getValidatedQuery` | Read the query string, optionally [validated](#validation). |
42
+ | `readBody`, `readValidatedBody` | Read and parse the request body, optionally [validated](#validation). |
41
43
  | `getCookie`, `setCookie`, `deleteCookie` | Read and write cookies. |
42
44
  | `setResponseStatus` | Set the response status and reason phrase. |
43
- | `setResponseHeader`, `setResponseHeaders` | Set response headers. |
45
+ | `handleCors` | Apply [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) headers and answer preflight requests. |
44
46
  | `sendRedirect` | Redirect the request. |
45
47
  | `useSession`, `getSession`, `updateSession`, `clearSession` | Read and write a [sealed session cookie](#sessions). |
46
48
  | `deriveSecret` | A purpose-specific secret [derived from `appSecret`](#deriving-secrets). |
47
49
  | `getRouteRules` | The [route rules](/docs/guide/concepts/rendering#route-rules) matched for the request. |
48
50
  | `useRuntimeConfig` | The server's [runtime configuration](/docs/guide/going-further/runtime-config). |
51
+ | `useAppConfig` | The [app config](/docs/directory-structure/app/app-config), as a copy per request when passed the event. |
49
52
  | `toNuxtRequestEvent` | The event in the shape the server runtime provides. |
50
53
 
51
- Types are exported alongside the utilities: `RequestEvent`, `RequestEventContext`, `NuxtRequestEvent`, `EventHandler`, `AppRouteRules`, `ServerRoutes`, `NuxtError`, `NuxtErrorDetails`, `NuxtErrorJSON`, `NuxtErrorLike`, `Session`, `SessionConfig`, `SessionData`, `SessionEvent`, `SessionManager`, `SessionPassword` and `SessionUpdate`.
54
+ Types are exported alongside the utilities: `RequestEvent`, `RequestEventContext`, `NuxtRequestEvent`, `EventHandler`, `AppRouteRules`, `ServerRoutes`, `CorsOptions`, `ValidateResult`, `NuxtError`, `NuxtErrorDetails`, `NuxtErrorJSON`, `NuxtErrorLike`, `Session`, `SessionConfig`, `SessionData`, `SessionEvent`, `SessionManager`, `SessionPassword` and `SessionUpdate`.
52
55
 
53
- These names are [auto-imported](/docs/directory-structure/server) in server code, so the import statement above is optional. Writing it keeps the file working in a project with server auto-imports off, and is what a module should do.
56
+ These names, except `useAppConfig`, are [auto-imported](/docs/directory-structure/server) in server code, so the import statement above is optional. Writing it keeps the file working in a project with server auto-imports off, and is what a module should do.
54
57
 
55
58
  ::tip
56
59
  `defineEventHandler` preserves your handler's return type, which is what types [`$fetch` and `useFetch`](/docs/getting-started/data-fetching) calls to the route. Annotate the value you return rather than the handler.
@@ -69,6 +72,8 @@ interface RequestEvent {
69
72
  }
70
73
  ```
71
74
 
75
+ To set, read, append or remove a response header, use `event.res.headers` directly: it is a standard `Headers` object.
76
+
72
77
  Nitro adds more on top, such as `event.node`, `event.runtime` and `event.waitUntil()`, but these four core properties work in all runtimes, and need no helpers:
73
78
 
74
79
  ```ts [server/api/echo.post.ts]
@@ -80,6 +85,28 @@ export default defineEventHandler(async (event) => {
80
85
 
81
86
  `NuxtRequestEvent` is the same request in the shape the configured builder provides, which is h3's `H3Event` under `@nuxt/nitro-server`. You can get a type-safe version of the event for the server builder you're using by calling `toNuxtRequestEvent(event)`.
82
87
 
88
+ ## Validation
89
+
90
+ `readValidatedBody` and `getValidatedQuery` take any [Standard Schema](https://standardschema.dev) (Zod, Valibot, ArkType and others), or a function that returns the validated value, `true` to accept the input or `false` to reject it.
91
+
92
+ ```ts [server/api/users.post.ts]
93
+ import { defineEventHandler, readValidatedBody } from 'nuxt/server'
94
+ import { z } from 'zod'
95
+
96
+ export default defineEventHandler(async (event) => {
97
+ const user = await readValidatedBody(event, z.object({ name: z.string() }))
98
+ return { created: user.name }
99
+ })
100
+ ```
101
+
102
+ Invalid input is rejected with a `400` whose `data.issues` lists what failed. Pass `onError` to reject it with a different error.
103
+
104
+ ## Client IP
105
+
106
+ `getRequestIP(event)` returns the address the server runtime reports for the connection, or `undefined` if it reports none. No forwarded header is trusted by default, because a client can send any value in one.
107
+
108
+ Behind a proxy you control, pass `{ xForwardedFor: true }` to read the first entry of `X-Forwarded-For` instead. Only do this when the proxy overwrites the header: a proxy that appends to it leaves a client-sent value first.
109
+
83
110
  ## Sessions
84
111
 
85
112
  `useSession` reads the session for the request, sealing a new one into a cookie when there is none to read. The data is sealed with [iron](https://github.com/brc-dd/iron-webcrypto), so it lives in the cookie rather than in server storage, and the cookie defaults to `httpOnly`, `secure`, `sameSite: 'lax'` and `path: '/'`.
@@ -126,52 +153,48 @@ Most of those helpers take the event as it is:
126
153
 
127
154
  ```ts [server/api/upload.post.ts]
128
155
  import { defineEventHandler } from 'nuxt/server'
129
- import { readValidatedBody } from 'nitro/h3'
156
+ import { readMultipartFormData } from 'nitro/h3'
130
157
 
131
158
  export default defineEventHandler(async (event) => {
132
- const body = await readValidatedBody(event, schema)
133
- return { received: body }
159
+ const parts = await readMultipartFormData(event)
160
+ return { received: parts?.length ?? 0 }
134
161
  })
135
162
  ```
136
163
 
137
- That works for any h3 helper that only reads the request: `readValidatedBody`, `getValidatedQuery`, `getRouterParam`, `getRouterParams`, `getRequestIP` and `assertMethod`.
164
+ That works for any h3 helper that only reads the request, such as `readRawBody`, `readFormData`, `readMultipartFormData` and `assertMethod`.
138
165
 
139
166
  A helper that needs the runtime's own event gets it from `toNuxtRequestEvent`:
140
167
 
141
- ```ts [server/api/cors.ts]
168
+ ```ts [server/api/proxy.ts]
142
169
  import { defineEventHandler, toNuxtRequestEvent } from 'nuxt/server'
143
- import { handleCors } from 'nitro/h3'
170
+ import { proxyRequest } from 'nitro/h3'
144
171
 
145
- export default defineEventHandler((event) => {
146
- handleCors(toNuxtRequestEvent(event), { origin: '*' })
147
- return { ok: true }
148
- })
172
+ export default defineEventHandler(event => proxyRequest(toNuxtRequestEvent(event), 'https://example.com'))
149
173
  ```
150
174
 
151
- Helpers that need you to call `toNuxtRequestEvent` are the CORS helpers (such as `handleCors`), `proxy`, `proxyRequest`, `fetchWithEvent`, `writeEarlyHints`, and reading `event.node`, `event.waitUntil()` or `event.runtime`. The helper works on every builder, and a cast to `NuxtRequestEvent` is safe even if the runtime's event is web-shaped, as it is under `@nuxt/nitro-server`.
175
+ Helpers that need you to call `toNuxtRequestEvent` are `proxy`, `proxyRequest`, `fetchWithEvent`, `writeEarlyHints`, and reading `event.node`, `event.waitUntil()` or `event.runtime`. The helper works on every builder, and a cast to `NuxtRequestEvent` is safe even if the runtime's event is web-shaped, as it is under `@nuxt/nitro-server`.
152
176
 
153
177
  Nitro's own APIs mostly take no event at all: `getRouteRules(method, pathname)`, `serverFetch()`, `defineCachedHandler()`, `useStorage()`, `useDatabase()` and tasks.
154
178
 
155
179
  ::tip
156
180
  If you find you are writing Nitro-specific code, you may simply prefer to import `defineEventHandler` from `nitro/h3` instead:
157
181
 
158
- ```ts [server/api/cors.ts]
159
- import { defineEventHandler, handleCors } from 'nitro/h3'
182
+ ```ts [server/api/proxy.ts]
183
+ import { defineEventHandler, proxyRequest } from 'nitro/h3'
160
184
 
161
- export default defineEventHandler((event) => {
162
- handleCors(event, { origin: '*' })
163
- return { ok: true }
164
- })
185
+ export default defineEventHandler(event => proxyRequest(event, 'https://example.com'))
165
186
  ```
166
187
  ::
167
188
 
168
189
  ## What Isn't Portable
169
190
 
170
- Three key areas you may need will mean you need to reach outside `nuxt/server`, because Nuxt can't provide them for every builder:
191
+ These areas mean reaching outside `nuxt/server`, because Nuxt can't provide them for every builder:
171
192
 
172
193
  - **Storage.** `useStorage()` comes from `nitro/storage`, and so does the driver configuration behind it.
173
- - **Sessions.** The sealed-session helpers come from `nitro/h3`. They accept the portable event, but importing them pins the file to Nitro.
174
- - **Caching.** `defineCachedHandler()` and `defineCachedFunction()` come from `nitro/cache`.
194
+ - **Caching.** `defineCachedHandler()` and `defineCachedFunction()` come from `nitro/cache`. For caching that runs anywhere, depend on a cache library directly.
195
+ - **Server plugins and hooks.** `definePlugin()` comes from `nitro`, and the runtime hooks (including `render:html`) from `useNitroHooks()` in `nitro/app`.
196
+ - **App-relative fetch.** `serverFetch()` comes from `nitro`. It calls a route of the app without an origin, which needs the runtime's router.
197
+ - **Lazy handlers.** `lazyEventHandler()` comes from `nitro/h3`.
175
198
 
176
199
  ## Server Code Only
177
200
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nuxt/docs-nightly",
3
- "version": "5.0.0-29837688.ef8d0fbb",
3
+ "version": "5.0.0-29837794.25b87beb",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/nuxt/nuxt.git",