@nuxt/docs-nightly 5.0.0-29554472.d5d8ce2f → 5.0.0-29555043.842b6927

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.
@@ -607,7 +607,6 @@ However, when calling `useFetch` with a relative URL on the server, Nuxt will us
607
607
  If you want to pass on/proxy cookies in the other direction, from an internal request back to the client, you will need to handle this yourself.
608
608
 
609
609
  ```ts [app/composables/fetch.ts]
610
- import { appendResponseHeader } from 'h3'
611
610
  import type { H3Event } from 'h3'
612
611
 
613
612
  export const fetchWithCookie = async (event: H3Event, url: string) => {
@@ -617,7 +616,7 @@ export const fetchWithCookie = async (event: H3Event, url: string) => {
617
616
  const cookies = res.headers.getSetCookie()
618
617
  /* Attach each cookie to our incoming Request */
619
618
  for (const cookie of cookies) {
620
- appendResponseHeader(event, 'set-cookie', cookie)
619
+ event.res.headers.append('set-cookie', cookie)
621
620
  }
622
621
  /* Return the data of the response */
623
622
  return res._data
@@ -29,6 +29,8 @@ You can easily manage the server-only part of your Nuxt app, from API endpoints
29
29
  Both endpoints and middleware can be defined like this:
30
30
 
31
31
  ```ts twoslash [server/api/test.ts]
32
+ import { defineEventHandler } from 'nitro/h3'
33
+
32
34
  export default defineEventHandler(async (event) => {
33
35
  // ... Do whatever you want here
34
36
  })
@@ -74,7 +76,7 @@ export default defineNuxtConfig({
74
76
  '/api/*': { cache: { maxAge: 60 * 60 } },
75
77
  // Redirection to avoid 404
76
78
  '/old-page': {
77
- redirect: { to: '/new-page', statusCode: 302 },
79
+ redirect: { to: '/new-page', status: 302 },
78
80
  },
79
81
  // ...
80
82
  },
@@ -203,6 +203,151 @@ Most of the migration is handled by Nuxt internally, but there are some user-fac
203
203
  See the full Vite 8 migration guide for all breaking changes and migration steps.
204
204
  ::
205
205
 
206
+ ### Migration to Nitro v3
207
+
208
+ 🚦 **Impact Level**: Significant
209
+
210
+ #### What Changed
211
+
212
+ Nuxt 5 upgrades to [Nitro v3](https://nitro.build/blog/v3-beta), which is a major rewrite of the server engine. Nitro v3 is built on [srvx](https://srvx.h3.dev) and [h3 v2](https://h3.dev), adopting Web standard `Request`/`Response` APIs throughout. This brings performance improvements and a more consistent API, but includes several breaking changes to server-side code.
213
+
214
+ ::important
215
+ We are still working on Nitro v3 integration so you should expect further changes, as well as additional work to make migration more straightforward.
216
+ ::
217
+
218
+ ::read-more{to="https://nitro.build/blog/v3-beta" target="_blank"}
219
+ Read the Nitro v3 beta announcement for a full overview.
220
+ ::
221
+
222
+ ::read-more{to="https://nitro.build/docs/migration" target="_blank"}
223
+ See the full Nitro v3 migration guide for all breaking changes.
224
+ ::
225
+
226
+ The sections below highlight changes that are most relevant to Nuxt application developers and module authors.
227
+
228
+ #### Package and Import Path Changes
229
+
230
+ The `nitropack` package has been renamed to `nitro`. All import paths have changed:
231
+
232
+ | Before | After |
233
+ |---|---|
234
+ | `nitropack` | `nitro` |
235
+ | `nitropack/types` | `nitro/types` |
236
+ | `nitropack/runtime` | `nitro/runtime` |
237
+ | `h3` (for server utilities) | `nitro/h3` |
238
+
239
+ Auto-imports within server routes (`defineEventHandler`, `getQuery`, `readBody`, `useRuntimeConfig`, etc.) continue to work without changes.
240
+
241
+ If you have explicit imports in server code, update them:
242
+
243
+ ```diff
244
+ - import { defineEventHandler, getQuery } from 'h3'
245
+ + import { defineEventHandler, getQuery } from 'nitro/h3'
246
+ ```
247
+
248
+ **For module authors**, type augmentations must target the new module path:
249
+
250
+ ```diff
251
+ - declare module 'nitropack/types' {
252
+ + declare module 'nitro/types' {
253
+ interface NitroRouteRules {
254
+ myModule?: { /* ... */ }
255
+ }
256
+ }
257
+ ```
258
+
259
+ #### Error Handling: `status`/`statusText` replace `statusCode`/`statusMessage`
260
+
261
+ h3 v2 renames the error properties to align with Web standards:
262
+
263
+ ```diff
264
+ createError({
265
+ - statusCode: 404,
266
+ - statusMessage: 'Not Found',
267
+ + status: 404,
268
+ + statusText: 'Not Found',
269
+ })
270
+ ```
271
+
272
+ In server routes, the error class is now `HTTPError` (replacing `createError` from `h3`):
273
+
274
+ ```diff
275
+ - import { createError } from 'h3'
276
+ + import { HTTPError } from 'nitro/h3'
277
+
278
+ export default defineEventHandler(() => {
279
+ - throw createError({ statusCode: 400, statusMessage: 'Bad request' })
280
+ + throw new HTTPError({ status: 400, statusText: 'Bad request' })
281
+ })
282
+ ```
283
+
284
+ ::note
285
+ In the Vue part of your app (the `app/` directory), Nuxt's `createError` composable continues to work and is the recommended way to throw errors.
286
+ ::
287
+
288
+ #### Server Event API Changes (h3 v2)
289
+
290
+ The `H3Event` object now uses Web standard APIs:
291
+
292
+ **Request properties:**
293
+ ```diff
294
+ - event.path // string
295
+ + event.url.pathname // URL object - use .pathname, .search, .hash
296
+
297
+ - event.method // string
298
+ + event.req.method // via Web Request object
299
+
300
+ - event.node.req.headers // Node.js IncomingHttpHeaders
301
+ + event.req.headers // Web Headers API (.get(), .set(), .has())
302
+ ```
303
+
304
+ **Response properties:**
305
+ ```diff
306
+ - event.node.res.statusCode = 200
307
+ + event.res.status = 200
308
+
309
+ - event.node.res.statusMessage = 'OK'
310
+ + event.res.statusText = 'OK'
311
+
312
+ - setResponseHeader(event, 'x-custom', 'value')
313
+ + event.res.headers.set('x-custom', 'value')
314
+
315
+ - appendResponseHeader(event, 'set-cookie', cookie)
316
+ + event.res.headers.append('set-cookie', cookie)
317
+ ```
318
+
319
+ #### `useRuntimeConfig()` No Longer Accepts `event`
320
+
321
+ In Nitro v3, `useRuntimeConfig()` no longer requires (or accepts) an `event` argument in server routes:
322
+
323
+ ```diff
324
+ export default defineEventHandler((event) => {
325
+ - const config = useRuntimeConfig(event)
326
+ + const config = useRuntimeConfig()
327
+ })
328
+ ```
329
+
330
+ #### Route Rules: `statusCode` Renamed to `status`
331
+
332
+ If you define redirect route rules, the property name has changed:
333
+
334
+ ```diff
335
+ export default defineNuxtConfig({
336
+ routeRules: {
337
+ '/old-page': {
338
+ - redirect: { to: '/new-page', statusCode: 302 },
339
+ + redirect: { to: '/new-page', status: 302 },
340
+ },
341
+ },
342
+ })
343
+ ```
344
+
345
+ #### For Module Authors: Additional Changes
346
+
347
+ - **Nitro plugin imports**: Use `import { defineNitroPlugin } from 'nitro/runtime'` for explicit imports (auto-imports still work).
348
+ - **Runtime hooks**: `nitroApp.hooks.hook('beforeResponse', ...)` and `nitroApp.hooks.hook('afterResponse', ...)` have been replaced by `nitroApp.hooks.hook('response', ...)`.
349
+ - **`getRouteRules()` from `nitro/app`**: On the server, the Nitro helper changed from `getRouteRules(event)` to `getRouteRules(method, pathname)`, which returns `{ routeRules }`.
350
+
206
351
  ### Non-Async `callHook`
207
352
 
208
353
  🚦 **Impact Level**: Minimal
@@ -37,10 +37,6 @@ interface NuxtError {
37
37
  statusText?: string
38
38
  data?: unknown
39
39
  cause?: unknown
40
- // legacy/deprecated equivalent of `status`
41
- statusCode: number
42
- // legacy/deprecated equivalent of `statusText`
43
- statusMessage?: string
44
40
  }
45
41
  ```
46
42
 
@@ -43,6 +43,8 @@ export default defineNuxtModule({
43
43
  ```
44
44
 
45
45
  ```ts twoslash [modules/hello/runtime/api-route.ts]
46
+ import { defineEventHandler } from 'nitro/h3'
47
+
46
48
  export default defineEventHandler(() => {
47
49
  return { hello: 'world' }
48
50
  })
@@ -19,9 +19,11 @@ Nuxt automatically scans files inside these directories to register API and serv
19
19
 
20
20
  Each file should export a default function defined with `defineEventHandler()` or `eventHandler()` (alias).
21
21
 
22
- The handler can directly return JSON data, a `Promise`, or use `event.node.res.end()` to send a response.
22
+ The handler can directly return JSON data, a `Promise`, or a `Response` object.
23
23
 
24
24
  ```ts twoslash [server/api/hello.ts]
25
+ import { defineEventHandler } from 'nitro/h3'
26
+
25
27
  export default defineEventHandler((event) => {
26
28
  return {
27
29
  hello: 'world',
@@ -322,7 +324,7 @@ export default defineEventHandler((event) => {
322
324
  ::code-group
323
325
  ```ts [server/api/foo.ts]
324
326
  export default defineEventHandler(async (event) => {
325
- const config = useRuntimeConfig(event)
327
+ const config = useRuntimeConfig()
326
328
 
327
329
  const repo = await $fetch('https://api.github.com/repos/nuxt/nuxt', {
328
330
  headers: {
@@ -144,7 +144,7 @@ export default defineNuxtModule({
144
144
  interface MyModuleNitroRules {
145
145
  myModule?: { foo: 'bar' }
146
146
  }
147
- declare module 'nitropack/types' {
147
+ declare module 'nitro/types' {
148
148
  interface NitroRouteRules extends MyModuleNitroRules {}
149
149
  interface NitroRouteConfig extends MyModuleNitroRules {}
150
150
  }
@@ -10,19 +10,46 @@ The [`$fetch`](/docs/4.x/api/utils/dollarfetch) utility function (used by the [`
10
10
 
11
11
  However, Nuxt provides a way to create a custom fetcher for your API (or multiple fetchers if you have multiple APIs to call).
12
12
 
13
- ## Custom `$fetch`
13
+ ## Recipe: API Client with Auth
14
14
 
15
- Let's create a custom `$fetch` instance with a [Nuxt plugin](/docs/4.x/directory-structure/app/plugins).
15
+ Let's say you have an external API at `https://api.nuxt.com` that requires JWT authentication via [nuxt-auth-utils](https://github.com/atinux/nuxt-auth-utils), and you want to redirect to `/login` on `401` responses.
16
+
17
+ ```ts [app/composables/useAPI.ts]
18
+ export const useAPI = createUseFetch({
19
+ baseURL: 'https://api.nuxt.com',
20
+ onRequest ({ options }) {
21
+ const { session } = useUserSession()
22
+ if (session.value?.token) {
23
+ options.headers.set('Authorization', `Bearer ${session.value.token}`)
24
+ }
25
+ },
26
+ async onResponseError ({ response }) {
27
+ if (response.status === 401) {
28
+ await navigateTo('/login')
29
+ }
30
+ },
31
+ })
32
+ ```
33
+
34
+ Now every call to `useAPI` automatically includes the auth header and handles 401 redirects:
35
+
36
+ ```vue [app/pages/dashboard.vue]
37
+ <script setup lang="ts">
38
+ const { data: profile } = await useAPI('/me')
39
+ const { data: orders } = await useAPI('/orders')
40
+ </script>
41
+ ```
42
+
43
+ :read-more{to="/docs/4.x/api/composables/create-use-fetch"}
44
+
45
+ ## Recipe: Custom `$fetch` Instance
46
+
47
+ If you need lower-level control, you can create a custom `$fetch` instance with a [Nuxt plugin](/docs/4.x/directory-structure/app/plugins) and either use it with `useAsyncData` directly or pass it to `createUseFetch`.
16
48
 
17
49
  ::note
18
50
  `$fetch` is a configured instance of [ofetch](https://github.com/unjs/ofetch) which supports adding the base URL of your Nuxt server as well as direct function calls during SSR (avoiding HTTP roundtrips).
19
51
  ::
20
52
 
21
- Let's pretend here that:
22
- - The main API is https://api.nuxt.com
23
- - We are storing the JWT token in a session with [nuxt-auth-utils](https://github.com/atinux/nuxt-auth-utils)
24
- - If the API responds with a `401` status code, we redirect the user to the `/login` page
25
-
26
53
  ```ts [app/plugins/api.ts]
27
54
  export default defineNuxtPlugin((nuxtApp) => {
28
55
  const { session } = useUserSession()
@@ -31,7 +58,6 @@ export default defineNuxtPlugin((nuxtApp) => {
31
58
  baseURL: 'https://api.nuxt.com',
32
59
  onRequest ({ request, options, error }) {
33
60
  if (session.value?.token) {
34
- // note that this relies on ofetch >= 1.4.0 - you may need to refresh your lockfile
35
61
  options.headers.set('Authorization', `Bearer ${session.value?.token}`)
36
62
  }
37
63
  },
@@ -42,7 +68,6 @@ export default defineNuxtPlugin((nuxtApp) => {
42
68
  },
43
69
  })
44
70
 
45
- // Expose to useNuxtApp().$api
46
71
  return {
47
72
  provide: {
48
73
  api,
@@ -51,7 +76,7 @@ export default defineNuxtPlugin((nuxtApp) => {
51
76
  })
52
77
  ```
53
78
 
54
- With this Nuxt plugin, `$api` is exposed from `useNuxtApp()` to make API calls directly from the Vue components:
79
+ You can then use the custom `$fetch` instance directly:
55
80
 
56
81
  ```vue [app/app.vue]
57
82
  <script setup>
@@ -61,65 +86,9 @@ const { data: modules } = await useAsyncData('modules', () => $api('/modules'))
61
86
  ```
62
87
 
63
88
  ::callout
64
- Wrapping with [`useAsyncData`](/docs/4.x/api/composables/use-async-data) **avoid double data fetching when doing server-side rendering** (server & client on hydration).
65
- ::
66
-
67
- ## Custom `useFetch`/`useAsyncData`
68
-
69
- Now that `$api` has the logic we want, let's create a `useAPI` composable to replace the usage of `useAsyncData` + `$api`:
70
-
71
- ```ts [app/composables/useAPI.ts]
72
- import type { UseFetchOptions } from 'nuxt/app'
73
-
74
- export function useAPI<T> (
75
- url: string | (() => string),
76
- options?: UseFetchOptions<T>,
77
- ) {
78
- return useFetch(url, {
79
- ...options,
80
- $fetch: useNuxtApp().$api as typeof $fetch,
81
- })
82
- }
83
- ```
84
-
85
- Let's use the new composable and have a nice and clean component:
86
-
87
- ```vue [app/app.vue]
88
- <script setup>
89
- const { data: modules } = await useAPI('/modules')
90
- </script>
91
- ```
92
-
93
- If you want to customize the type of any error returned, you can also do so:
94
-
95
- ```ts
96
- import type { FetchError } from 'ofetch'
97
- import type { UseFetchOptions } from 'nuxt/app'
98
-
99
- interface CustomError {
100
- message: string
101
- status: number
102
- }
103
-
104
- export function useAPI<T> (
105
- url: string | (() => string),
106
- options?: UseFetchOptions<T>,
107
- ) {
108
- return useFetch<T, FetchError<CustomError>>(url, {
109
- ...options,
110
- $fetch: useNuxtApp().$api,
111
- })
112
- }
113
- ```
114
-
115
- ::note
116
- This example demonstrates how to use a custom `useFetch`, but the same structure is identical for a custom `useAsyncData`.
89
+ Wrapping with [`useAsyncData`](/docs/4.x/api/composables/use-async-data) **avoids double data fetching when doing server-side rendering** (server & client on hydration).
117
90
  ::
118
91
 
119
92
  :link-example{to="/docs/4.x/examples/advanced/use-custom-fetch-composable"}
120
93
 
121
94
  :video-accordion{title="Watch a video about custom $fetch and Repository Pattern in Nuxt" videoId="jXH8Tr-exhI"}
122
-
123
- ::note
124
- We are currently discussing to find a cleaner way to let you create a custom fetcher, see https://github.com/nuxt/nuxt/issues/14736.
125
- ::
@@ -136,7 +136,7 @@ You can access runtime config within the server routes as well using `useRuntime
136
136
 
137
137
  ```ts [server/api/test.ts]
138
138
  export default defineEventHandler(async (event) => {
139
- const { apiSecret } = useRuntimeConfig(event)
139
+ const { apiSecret } = useRuntimeConfig()
140
140
  const result = await $fetch('https://my.api.com/test', {
141
141
  headers: {
142
142
  Authorization: `Bearer ${apiSecret}`,
@@ -90,7 +90,7 @@ declare module '#app' {
90
90
  }
91
91
  }
92
92
 
93
- declare module 'nitropack/types' {
93
+ declare module 'nitro/types' {
94
94
  interface NitroRuntimeHooks {
95
95
  'your-nitro-hook': () => void
96
96
  }
@@ -0,0 +1,90 @@
1
+ ---
2
+ title: 'createUseAsyncData'
3
+ description: A factory function to create a custom useAsyncData composable with pre-defined default options.
4
+ links:
5
+ - label: Source
6
+ icon: i-simple-icons-github
7
+ to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/composables/asyncData.ts
8
+ size: xs
9
+ ---
10
+
11
+ `createUseAsyncData` creates a custom [`useAsyncData`](/docs/4.x/api/composables/use-async-data) composable with pre-defined options. The resulting composable is fully typed and works exactly like `useAsyncData`, but with your defaults baked in.
12
+
13
+ ::note
14
+ `createUseAsyncData` is a compiler macro. It must be used as an **exported** declaration in the `composables/` directory (or any directory scanned by the Nuxt compiler). Nuxt automatically injects de-duplication keys at build time.
15
+ ::
16
+
17
+ ## Usage
18
+
19
+ ```ts [app/composables/useCachedData.ts]
20
+ export const useCachedData = createUseAsyncData({
21
+ getCachedData (key, nuxtApp) {
22
+ return nuxtApp.payload.data[key] ?? nuxtApp.static.data[key]
23
+ },
24
+ })
25
+ ```
26
+
27
+ ```vue [app/pages/index.vue]
28
+ <script setup lang="ts">
29
+ const { data: mountains } = await useCachedData(
30
+ 'mountains',
31
+ () => $fetch('https://api.nuxtjs.dev/mountains'),
32
+ )
33
+ </script>
34
+ ```
35
+
36
+ The resulting composable has the same signature and return type as [`useAsyncData`](/docs/4.x/api/composables/use-async-data), with all options available for the caller to use or override.
37
+
38
+ ## Type
39
+
40
+ ```ts [Signature]
41
+ function createUseAsyncData (
42
+ options?: Partial<AsyncDataOptions>,
43
+ ): typeof useAsyncData
44
+
45
+ function createUseAsyncData (
46
+ options: (callerOptions: AsyncDataOptions) => Partial<AsyncDataOptions>,
47
+ ): typeof useAsyncData
48
+ ```
49
+
50
+ ## Options
51
+
52
+ `createUseAsyncData` accepts all the same options as [`useAsyncData`](/docs/4.x/api/composables/use-async-data#params), including `server`, `lazy`, `immediate`, `default`, `transform`, `pick`, `getCachedData`, `deep`, `dedupe`, `timeout`, and `watch`.
53
+
54
+ See the full list of options in the [`useAsyncData` documentation](/docs/4.x/api/composables/use-async-data#params).
55
+
56
+ ## Default vs Override Mode
57
+
58
+ ### Default Mode (plain object)
59
+
60
+ When you pass a plain object, the factory options act as **defaults**. Callers can override any option:
61
+
62
+ ```ts [app/composables/useLazyData.ts]
63
+ export const useLazyData = createUseAsyncData({
64
+ lazy: true,
65
+ server: false,
66
+ })
67
+ ```
68
+
69
+ ```ts
70
+ // Uses the defaults (lazy: true, server: false)
71
+ const { data } = await useLazyData('key', () => fetchSomeData())
72
+
73
+ // Caller overrides server to true
74
+ const { data } = await useLazyData('key', () => fetchSomeData(), { server: true })
75
+ ```
76
+
77
+ ### Override Mode (function)
78
+
79
+ When you pass a function, the factory options **override** the caller's options. The function receives the caller's options as its argument:
80
+
81
+ ```ts [app/composables/useStrictData.ts]
82
+ // deep is always enforced as false
83
+ export const useStrictData = createUseAsyncData(callerOptions => ({
84
+ deep: false,
85
+ }))
86
+ ```
87
+
88
+ :read-more{to="/docs/4.x/guide/recipes/custom-usefetch"}
89
+
90
+ :read-more{to="/docs/4.x/api/composables/use-async-data"}
@@ -0,0 +1,97 @@
1
+ ---
2
+ title: 'createUseFetch'
3
+ description: A factory function to create a custom useFetch composable with pre-defined default options.
4
+ links:
5
+ - label: Source
6
+ icon: i-simple-icons-github
7
+ to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/composables/fetch.ts
8
+ size: xs
9
+ ---
10
+
11
+ `createUseFetch` creates a custom [`useFetch`](/docs/4.x/api/composables/use-fetch) composable with pre-defined options. The resulting composable is fully typed and works exactly like `useFetch`, but with your defaults baked in.
12
+
13
+ ::note
14
+ `createUseFetch` is a compiler macro. It must be used as an **exported** declaration in the `composables/` directory (or any directory scanned by the Nuxt compiler). Nuxt automatically injects de-duplication keys at build time.
15
+ ::
16
+
17
+ ## Usage
18
+
19
+ ```ts [app/composables/useAPI.ts]
20
+ export const useAPI = createUseFetch({
21
+ baseURL: 'https://api.nuxt.com',
22
+ })
23
+ ```
24
+
25
+ ```vue [app/pages/modules.vue]
26
+ <script setup lang="ts">
27
+ const { data: modules } = await useAPI('/modules')
28
+ </script>
29
+ ```
30
+
31
+ The resulting `useAPI` composable has the same signature and return type as [`useFetch`](/docs/4.x/api/composables/use-fetch), with all options available for the caller to use or override.
32
+
33
+ ## Type
34
+
35
+ ```ts [Signature]
36
+ function createUseFetch (
37
+ options?: Partial<UseFetchOptions>,
38
+ ): typeof useFetch
39
+
40
+ function createUseFetch (
41
+ options: (callerOptions: UseFetchOptions) => Partial<UseFetchOptions>,
42
+ ): typeof useFetch
43
+ ```
44
+
45
+ ## Options
46
+
47
+ `createUseFetch` accepts all the same options as [`useFetch`](/docs/4.x/api/composables/use-fetch#parameters), including `baseURL`, `headers`, `query`, `onRequest`, `onResponse`, `server`, `lazy`, `transform`, `getCachedData`, and more.
48
+
49
+ See the full list of options in the [`useFetch` documentation](/docs/4.x/api/composables/use-fetch#parameters).
50
+
51
+ ## Default vs Override Mode
52
+
53
+ ### Default Mode (plain object)
54
+
55
+ When you pass a plain object, the factory options act as **defaults**. Callers can override any option:
56
+
57
+ ```ts [app/composables/useAPI.ts]
58
+ export const useAPI = createUseFetch({
59
+ baseURL: 'https://api.nuxt.com',
60
+ lazy: true,
61
+ })
62
+ ```
63
+
64
+ ```ts
65
+ // Uses the default baseURL
66
+ const { data } = await useAPI('/modules')
67
+
68
+ // Caller overrides the baseURL
69
+ const { data } = await useAPI('/modules', { baseURL: 'https://other-api.com' })
70
+ ```
71
+
72
+ ### Override Mode (function)
73
+
74
+ When you pass a function, the factory options **override** the caller's options. The function receives the caller's options as its argument, so you can read them to compute your overrides:
75
+
76
+ ```ts [app/composables/useAPI.ts]
77
+ // baseURL is always enforced, regardless of what the caller passes
78
+ export const useAPI = createUseFetch(callerOptions => ({
79
+ baseURL: 'https://api.nuxt.com',
80
+ }))
81
+ ```
82
+
83
+ This is useful for enforcing settings like authentication headers or a specific base URL that should not be changed by the caller.
84
+
85
+ ## Combining with a Custom `$fetch`
86
+
87
+ You can pass a custom `$fetch` instance to `createUseFetch`:
88
+
89
+ ```ts [app/composables/useAPI.ts]
90
+ export const useAPI = createUseFetch({
91
+ $fetch: useNuxtApp().$api as typeof $fetch,
92
+ })
93
+ ```
94
+
95
+ :read-more{to="/docs/4.x/guide/recipes/custom-usefetch"}
96
+
97
+ :read-more{to="/docs/4.x/api/composables/use-fetch"}
@@ -25,8 +25,8 @@ const { data, status, pending, error, refresh, clear } = await useAsyncData(
25
25
  </script>
26
26
  ```
27
27
 
28
- ::warning{to="/docs/4.x/guide/recipes/custom-usefetch#custom-usefetchuseasyncdata"}
29
- If you're using a custom `useAsyncData` wrapper, do not await it in the composable as that can cause unexpected behavior. See recipe for custom async data fetcher.
28
+ ::tip{to="/docs/4.x/guide/recipes/custom-usefetch#custom-usefetch-with-createusefetch"}
29
+ Need a custom `useAsyncData` with pre-defined defaults? Use `createUseAsyncData` to create a fully typed custom composable. See the [custom useFetch recipe](/docs/4.x/guide/recipes/custom-usefetch) for details.
30
30
  ::
31
31
 
32
32
  ::note
@@ -25,8 +25,8 @@ const { data, status, error, refresh, clear } = await useFetch('/api/modules', {
25
25
  </script>
26
26
  ```
27
27
 
28
- ::warning{to="/docs/4.x/guide/recipes/custom-usefetch#custom-usefetchuseasyncdata"}
29
- If you're using a custom `useFetch` wrapper, do not await it in the composable as that can cause unexpected behavior. See recipe for custom async data fetcher.
28
+ ::tip{to="/docs/4.x/guide/recipes/custom-usefetch#custom-usefetch-with-createusefetch"}
29
+ Need a custom `useFetch` with pre-defined defaults (like `baseURL` or auth headers)? Use `createUseFetch` to create a fully typed custom composable.
30
30
  ::
31
31
 
32
32
  ::note
@@ -87,7 +87,7 @@ Keyed state created using `useFetch` can be retrieved across your Nuxt applicati
87
87
  ::
88
88
 
89
89
  ::warning
90
- `useFetch` is a reserved function name transformed by the compiler, so you should not name your own function `useFetch`.
90
+ `useFetch` is a reserved function name transformed by the compiler, so you should not name your own function `useFetch`. To create a custom variant with pre-defined options, use [`createUseFetch`](/docs/4.x/guide/recipes/custom-usefetch#custom-usefetch-with-createusefetch) instead.
91
91
  ::
92
92
 
93
93
  ::warning
@@ -151,7 +151,6 @@ type UseFetchOptions<DataT> = {
151
151
  pick?: string[]
152
152
  $fetch?: typeof globalThis.$fetch
153
153
  watch?: MultiWatchSources | false
154
- timeout?: MaybeRefOrGetter<number>
155
154
  }
156
155
 
157
156
  type AsyncDataRequestContext = {
@@ -193,7 +192,6 @@ type AsyncDataRequestStatus = 'idle' | 'pending' | 'success' | 'error'
193
192
  | `body` | `MaybeRefOrGetter<RequestInit['body'] \| Record<string, any>>` | - | Request body. Objects are automatically stringified. |
194
193
  | `headers` | `MaybeRefOrGetter<Record<string, string> \| [key, value][] \| Headers>` | - | Request headers. |
195
194
  | `baseURL` | `MaybeRefOrGetter<string>` | - | Base URL for the request. |
196
- | `timeout` | `MaybeRefOrGetter<number>` | - | Timeout in milliseconds to abort the request. |
197
195
  | `cache` | `boolean \| string` | - | Cache control. Boolean disables cache, or use Fetch API values: `default`, `no-store`, etc. |
198
196
  | `server` | `boolean` | `true` | Whether to fetch on the server. |
199
197
  | `lazy` | `boolean` | `false` | If true, resolves after route loads (does not block navigation). |
@@ -18,7 +18,7 @@ const config = useRuntimeConfig()
18
18
 
19
19
  ```ts [server/api/foo.ts]
20
20
  export default defineEventHandler((event) => {
21
- const config = useRuntimeConfig(event)
21
+ const config = useRuntimeConfig()
22
22
  })
23
23
  ```
24
24
 
@@ -56,7 +56,7 @@ To access runtime config, we can use `useRuntimeConfig()` composable:
56
56
 
57
57
  ```ts [server/api/test.ts]
58
58
  export default defineEventHandler(async (event) => {
59
- const config = useRuntimeConfig(event)
59
+ const config = useRuntimeConfig()
60
60
 
61
61
  // Access public variables
62
62
  const result = await $fetch(`/test`, {
@@ -132,7 +132,7 @@ And then access the new CDN url using `config.app.cdnURL`.
132
132
 
133
133
  ```ts [server/api/foo.ts]
134
134
  export default defineEventHandler((event) => {
135
- const config = useRuntimeConfig(event)
135
+ const config = useRuntimeConfig()
136
136
 
137
137
  // Access cdnURL universally
138
138
  const cdnURL = config.app.cdnURL
@@ -73,6 +73,8 @@ export default defineNuxtModule({
73
73
  ```
74
74
 
75
75
  ```ts twoslash [runtime/robots.get.ts]
76
+ import { defineEventHandler } from 'nitro/h3'
77
+
76
78
  export default defineEventHandler(() => {
77
79
  return {
78
80
  body: `User-agent: *\nDisallow: /`,
@@ -96,7 +98,7 @@ Adds a Nitro server handler to be used only in development mode. This handler wi
96
98
  ### Usage
97
99
 
98
100
  ```ts twoslash
99
- import { defineEventHandler } from 'h3'
101
+ import { defineEventHandler } from 'nitro/h3'
100
102
  import { addDevServerHandler, createResolver, defineNuxtModule } from '@nuxt/kit'
101
103
 
102
104
  export default defineNuxtModule({
@@ -117,7 +119,7 @@ export default defineNuxtModule({
117
119
 
118
120
  ```ts twoslash
119
121
  // @errors: 2391
120
- import type { NitroDevEventHandler } from 'nitropack/types'
122
+ import type { NitroDevEventHandler } from 'nitro/types'
121
123
  // ---cut---
122
124
  function addDevServerHandler (handler: NitroDevEventHandler): void
123
125
  ```
@@ -198,7 +200,7 @@ You can read more about Nitro plugins in the [Nitro documentation](https://nitro
198
200
  ::
199
201
 
200
202
  ::warning
201
- It is necessary to explicitly import `defineNitroPlugin` from `nitropack/runtime` within your plugin file. The same requirement applies to utilities such as `useRuntimeConfig`.
203
+ It is necessary to explicitly import `defineNitroPlugin` from `nitro/runtime` within your plugin file. The same requirement applies to utilities such as `useRuntimeConfig`.
202
204
  ::
203
205
 
204
206
  ### Usage
@@ -242,17 +244,15 @@ export default defineNuxtModule({
242
244
  ```
243
245
 
244
246
  ```ts [runtime/plugin.ts]
247
+ import { defineNitroPlugin } from 'nitro/runtime'
248
+
245
249
  export default defineNitroPlugin((nitroApp) => {
246
250
  nitroApp.hooks.hook('request', (event) => {
247
- console.log('on request', event.path)
248
- })
249
-
250
- nitroApp.hooks.hook('beforeResponse', (event, { body }) => {
251
- console.log('on response', event.path, { body })
251
+ console.log('on request', event.req.url)
252
252
  })
253
253
 
254
- nitroApp.hooks.hook('afterResponse', (event, { body }) => {
255
- console.log('on after response', event.path, { body })
254
+ nitroApp.hooks.hook('response', async (res) => {
255
+ console.log('on response', await res.text())
256
256
  })
257
257
  })
258
258
  ```
@@ -415,6 +415,8 @@ export function useApiSecret () {
415
415
  You can then use the `useApiSecret` function in your server code:
416
416
 
417
417
  ```ts twoslash [runtime/server/api/hello.ts]
418
+ import { defineEventHandler } from 'nitro/h3'
419
+
418
420
  const useApiSecret = (): string => ''
419
421
  // ---cut---
420
422
  export default defineEventHandler(() => {
@@ -493,6 +495,8 @@ export function hello () {
493
495
  You can then use the `hello` function in your server code.
494
496
 
495
497
  ```ts twoslash [runtime/server/api/hello.ts]
498
+ import { defineEventHandler } from 'nitro/h3'
499
+
496
500
  function hello () {
497
501
  return 'Hello from server utils!'
498
502
  }
@@ -88,7 +88,7 @@ export default defineNuxtModule({
88
88
  extendRouteRules('/preview', {
89
89
  redirect: {
90
90
  to: '/preview-new',
91
- statusCode: 302,
91
+ status: 302,
92
92
  },
93
93
  })
94
94
 
@@ -1494,9 +1494,9 @@ Modules to generate deep aliases for within `compilerOptions.paths`. This does n
1494
1494
  - **Default**
1495
1495
  ```json
1496
1496
  [
1497
- "nitropack/types",
1498
- "nitropack/runtime",
1499
- "nitropack",
1497
+ "nitro/types",
1498
+ "nitro/runtime",
1499
+ "nitro",
1500
1500
  "defu",
1501
1501
  "h3",
1502
1502
  "consola",
@@ -42,7 +42,7 @@ console.log(config.public.apiBase)
42
42
 
43
43
  ```ts [server/api/hello.ts]
44
44
  export default defineEventhandler((event) => {
45
- const config = useRuntimeConfig(event)
45
+ const config = useRuntimeConfig()
46
46
  // In server, you can now access config.apiSecret, in addition to config.public
47
47
  console.log(config.apiSecret)
48
48
  console.log(config.public.apiBase)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nuxt/docs-nightly",
3
- "version": "5.0.0-29554472.d5d8ce2f",
3
+ "version": "5.0.0-29555043.842b6927",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/nuxt/nuxt.git",