@nuxt/docs-nightly 5.0.0-29805604.ff4efc9e → 5.0.0-29805621.06b691a8

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.
@@ -675,6 +675,137 @@ Using `<script setup>` or `<script setup lang="ts">` are the recommended way of
675
675
 
676
676
  :read-more{to="/docs/4.x/api/utils/define-nuxt-component"}
677
677
 
678
+ ## Typed Routes
679
+
680
+ `$fetch` and [`useFetch`](/docs/4.x/api/composables/use-fetch) are typed from the routes known to your server, so a
681
+ response is automatically typed based on its handler's return type.
682
+
683
+ ```ts [server/api/todos.get.ts]
684
+ export default defineEventHandler(() => [{ id: '1', title: 'Buy milk' }])
685
+ ```
686
+
687
+ ```ts
688
+ const todos = await $fetch('/api/todos')
689
+ // ^? { id: string, title: string }[]
690
+ ```
691
+
692
+ The method decides which handler responds, so `/api/todos` fetched with `POST` is typed by
693
+ `server/api/todos.post.ts` rather than by the `GET` handler above.
694
+
695
+ If a handler validates its request, this is typed for you when you fetch from that route. This works with
696
+ any [Standard Schema](https://standardschema.dev) library:
697
+
698
+ ```ts [server/api/todos.post.ts]
699
+ import { z } from 'zod'
700
+
701
+ export default defineValidatedHandler({
702
+ validate: { body: z.object({ title: z.string() }) },
703
+ handler: () => ({ id: '1' }),
704
+ })
705
+ ```
706
+
707
+ ```ts
708
+ await $fetch('/api/todos', { method: 'POST', body: { title: 'Buy milk' } })
709
+ await $fetch('/api/todos', { method: 'POST', body: { title: 42 } })
710
+ // ^ not assignable to string
711
+ await $fetch('/api/todos', { method: 'POST' })
712
+ // ^ body is required
713
+ ```
714
+
715
+ ### Requests Nuxt Cannot Type
716
+
717
+ A path built at runtime, an absolute URL and a `Request` object all resolve to `unknown`, because
718
+ there is nothing to match them against. In this case you can provide an explicit return type:
719
+
720
+ ```ts
721
+ const data = await $fetch<{ id: string }>(`/api/${resource}`)
722
+ ```
723
+
724
+ By default a path that Nuxt does not handle is typed as `unknown`, since a nitro middleware, a
725
+ [`routeRules`](/docs/4.x/guide/concepts/rendering#hybrid-rendering) proxy or a catch-all handler can answer it.
726
+ Enable [`experimental.strictRouteTypes`](/docs/4.x/guide/going-further/experimental-features#strictroutetypes)
727
+ to make an unrecognized path an error instead.
728
+
729
+ ### Requests Made With a `baseURL`
730
+
731
+ A `baseURL` is prepended to the path before the request is made, so it is part of the route being
732
+ requested and Nuxt resolves it as such - whether it is set per call, on a `$fetch` instance, or on a
733
+ composable built with `createUseFetch`:
734
+
735
+ ```ts
736
+ await $fetch('/todos', { baseURL: '/api' })
737
+ // ^? { id: string, title: string }[] - resolved as /api/todos
738
+
739
+ const api = $fetch.create({ baseURL: '/api' })
740
+ await api('/todos')
741
+ // ^? the same
742
+ ```
743
+
744
+ Since the path is resolved against the base, passing a path that already carries it is an error
745
+ naming the URL that would be requested:
746
+
747
+ ```ts
748
+ await $fetch('/api/todos', { baseURL: '/api' })
749
+ // ^ no GET route matches '/api/api/todos'
750
+ ```
751
+
752
+ A base Nuxt cannot read - a runtime value, a `ref` or a getter - leaves the request typed as
753
+ `unknown` rather than rejected, since there is nothing to resolve the path against. The same is true
754
+ of a base pointing at another origin, so an external API is fetched the way it always was:
755
+
756
+ ```ts
757
+ const users = await $fetch('/users', { baseURL: 'https://api.example.com' })
758
+ // ^? unknown
759
+ ```
760
+
761
+ ### Declaring Route Types
762
+
763
+ A route Nuxt does not learn about from your server builder - one a nitro plugin registers at
764
+ runtime, or an external API you want typed the same way - can be declared by augmenting
765
+ `ServerRoutes`:
766
+
767
+ ```ts [shared/server-routes.d.ts]
768
+ import type { Endpoint } from 'nuxt/app'
769
+
770
+ declare module '@nuxt/schema' {
771
+ interface ServerRoutes {
772
+ '/api/hello': {
773
+ [Endpoint]: {
774
+ GET: { response: { message: string } }
775
+ }
776
+ }
777
+ }
778
+ }
779
+ ```
780
+
781
+ Declare it in a `.d.ts` file your app compiles - `shared/` is visible to both app and server code -
782
+ and the route is resolved at the call site, though it does not appear in editor completions.
783
+
784
+ ::note
785
+ Modules that register handlers with [`addServerHandler`](/docs/4.x/api/kit/nitro#addserverhandler)
786
+ need no augmentation: those routes are reported by the server builder like any other, and typed
787
+ automatically.
788
+ ::
789
+
790
+ ### Writing Your Own Wrapper
791
+
792
+ To build a `useFetch` with different defaults, use
793
+ [`createUseFetch`](/docs/4.x/guide/recipes/custom-usefetch#custom-usefetch-with-createusefetch),
794
+ which keeps the route typing intact:
795
+
796
+ ```ts [app/composables/useApiFetch.ts]
797
+ export const useApiFetch = createUseFetch({ baseURL: '/api' })
798
+ ```
799
+
800
+ ```ts
801
+ const { data } = useApiFetch('/todos')
802
+ // ^? { id: string, title: string }[] - resolved as /api/todos
803
+ ```
804
+
805
+ If you are wrapping `$fetch` by hand, constrain the path by `string` rather than by
806
+ `TypedFetchRequest`, so that a route declared through augmentation is still accepted, and pass the
807
+ request through to `$fetch` so it is typed there.
808
+
678
809
  ## Serializing Data From Server to Client
679
810
 
680
811
  When using `useAsyncData` and `useLazyAsyncData` to transfer data fetched on server to the client (as well as anything else that utilizes [the Nuxt payload](/docs/4.x/api/composables/use-nuxt-app#payload)), the payload is serialized with [`devalue`](https://github.com/sveltejs/devalue). This allows us to transfer not just basic JSON but also to serialize and revive/deserialize more advanced kinds of data, such as regular expressions, Dates, Map and Set, `ref`, `reactive`, `shallowRef`, `shallowReactive` and `NuxtError` - and more.
@@ -902,6 +902,66 @@ export default defineNuxtConfig({
902
902
  })
903
903
  ```
904
904
 
905
+ ### Typed `$fetch` Rebuilt on Generated Route Types
906
+
907
+ 🚦 **Impact Level**: Medium
908
+
909
+ #### What Changed
910
+
911
+ `$fetch` and `useFetch` are typed from the routes Nuxt's server builder reports, rather than from
912
+ nitro's `InternalApi` interface. As well as response types, a `body`, `query` or `headers` the
913
+ matching handler validates are now enforced on the call, and a method the route does not handle is
914
+ rejected.
915
+
916
+ Two things follow from this:
917
+
918
+ - Routes you augmented by hand on nitro's `InternalApi` are no longer picked up. Augment
919
+ `ServerRoutes` from `@nuxt/schema` instead.
920
+ - The `params` option is no longer accepted by `$fetch` or `useFetch`. It was an alias for `query`.
921
+
922
+ #### Reasons for Change
923
+
924
+ Nitro v3 dropped typed fetch, and the old implementation did not scale past about 300 routes. The new
925
+ generated route types cost the same to check whatever the route count, and carry enough information to type the
926
+ request as well as the response. `params` is dropped so the name is free for named route parameters
927
+ later.
928
+
929
+ #### Migration Steps
930
+
931
+ Move any `params` option to `query`:
932
+
933
+ ```diff
934
+ const { data } = await useFetch('/api/search', {
935
+ - params: { q: 'nuxt' },
936
+ + query: { q: 'nuxt' },
937
+ })
938
+ ```
939
+
940
+ Move any manual route augmentation from `InternalApi` to `ServerRoutes`:
941
+
942
+ ```diff [shared/server-routes.d.ts]
943
+ - declare module 'nitropack' {
944
+ - interface InternalApi {
945
+ - '/api/hello': { get: { message: string } }
946
+ - }
947
+ - }
948
+ + import type { Endpoint } from 'nuxt/app'
949
+ +
950
+ + declare module '@nuxt/schema' {
951
+ + interface ServerRoutes {
952
+ + '/api/hello': {
953
+ + [Endpoint]: {
954
+ + GET: { response: { message: string } }
955
+ + }
956
+ + }
957
+ + }
958
+ + }
959
+ ```
960
+
961
+ ::read-more{to="/docs/4.x/getting-started/data-fetching#typed-routes"}
962
+ Read more about typed routes.
963
+ ::
964
+
905
965
  ### TypeScript `baseUrl` Is Ignored
906
966
 
907
967
  🚦 **Impact Level**: Minimal
@@ -406,6 +406,64 @@ You can even get typed params within a page by using `const route = useRoute('ro
406
406
 
407
407
  :video-accordion{title="Watch a video from Daniel Roe explaining type-safe routing in Nuxt" videoId="SXk-L19gTZk"}
408
408
 
409
+ ## strictRouteTypes
410
+
411
+ Reject a request to a path no server route answers.
412
+
413
+ ```ts twoslash [nuxt.config.ts]
414
+ export default defineNuxtConfig({
415
+ experimental: {
416
+ strictRouteTypes: true,
417
+ },
418
+ })
419
+ ```
420
+
421
+ Nuxt types `$fetch` and `useFetch` from the routes your server will serve, whatever this option is
422
+ set to, so a response is typed by the handler that answers it. What the option decides is whether a
423
+ path Nuxt does not recognise is an error or is simply typed as `unknown`.
424
+
425
+ - `false` (default) - a path Nuxt does not recognise is accepted and resolves to `unknown`, and no
426
+ method is rejected. Nuxt cannot see every way a request may be answered: nitro middleware, a
427
+ [`routeRules`](/docs/4.x/guide/concepts/rendering#hybrid-rendering) proxy or a catch-all handler can answer
428
+ a path no route describes.
429
+ - `true` - only the routes your server builder reports are accepted, for the methods they answer.
430
+ - `'isomorphic'` - as `true`, and your pages are included as `GET` routes returning `string`, so
431
+ `$fetch('/about')` is typed by the route the Vue router serves rather than rejected.
432
+
433
+ With the option on, a typo and a method the route does not answer are both errors:
434
+
435
+ ```ts
436
+ // server/api/todos.post.ts answers POST only
437
+ await $fetch('/api/todos', { method: 'POST' })
438
+ await $fetch('/api/todo', { method: 'POST' })
439
+ // ^ no POST route matches '/api/todo'
440
+ await $fetch('/api/todos')
441
+ // ^ no GET route matches '/api/todos'
442
+ ```
443
+
444
+ Two things stay accepted, because they are not Nuxt's to describe: an absolute URL
445
+ (`$fetch('https://example.com')`), and a path built at runtime, which resolves to `unknown` as it
446
+ does with the option off. A `baseURL` is resolved into the path before it is matched, so a request
447
+ made through one is checked against the route it actually asks for. Naming the response type also opts a call out, since doing so turns off
448
+ inference for the request:
449
+
450
+ ```ts
451
+ const data = await $fetch<{ id: string }>(`/api/${resource}`)
452
+ ```
453
+
454
+ ::note
455
+ Files in your `public/` directory are not routes your server builder reports, so requesting one
456
+ with `strictRouteTypes` enabled is an error. Fetch those with an explicit response type, or leave
457
+ the option off.
458
+ ::
459
+
460
+ Set this only where your routing is enumerable. An app with a catch-all page under `'isomorphic'`
461
+ matches every path, which is correct but means the option constrains nothing.
462
+
463
+ ::read-more{to="/docs/4.x/getting-started/data-fetching#typed-routes"}
464
+ Read more about typed routes, and about declaring a route Nuxt cannot see.
465
+ ::
466
+
409
467
  ## watcher
410
468
 
411
469
  Set an alternative watcher that will be used as the watching service for Nuxt.
@@ -41,6 +41,11 @@ function createUseFetch (
41
41
  function createUseFetch (
42
42
  options: (callerOptions: UseFetchOptions) => Partial<UseFetchOptions>,
43
43
  ): typeof useFetch
44
+
45
+ // where the client declares the routes it serves
46
+ function createUseFetch<Routes> (
47
+ options: Partial<UseFetchOptions> & { routes: Routes },
48
+ ): DeclaredUseFetch<Routes>
44
49
  ```
45
50
 
46
51
  ## Options
@@ -49,6 +54,67 @@ function createUseFetch (
49
54
 
50
55
  See the full list of options in the [`useFetch` documentation](/docs/4.x/api/composables/use-fetch#parameters).
51
56
 
57
+ ## Typing a Third-Party API
58
+
59
+ By default a composable created with `createUseFetch` is typed from the routes your own server
60
+ serves, so a request to another API resolves to `unknown`. Pass `routes` to say what that API serves,
61
+ and every request the composable makes is resolved against it instead:
62
+
63
+ ```ts [app/composables/usePetStore.ts]
64
+ import type { DynamicParam, Endpoint } from 'nuxt/app'
65
+
66
+ interface Pet { id: number, name: string }
67
+
68
+ interface PetStoreRoutes {
69
+ '/pets': {
70
+ [Endpoint]: {
71
+ GET: { response: Pet[], query: { limit?: number } }
72
+ POST: { response: Pet, body: { name: string } }
73
+ }
74
+ // a path parameter, matched positionally
75
+ [DynamicParam]: {
76
+ [Endpoint]: { GET: { response: Pet } }
77
+ }
78
+ }
79
+ }
80
+
81
+ export const usePetStore = createUseFetch({
82
+ baseURL: 'https://api.example.com',
83
+ routes: {} as PetStoreRoutes,
84
+ })
85
+ ```
86
+
87
+ ```ts
88
+ const { data: pets } = await usePetStore('/pets')
89
+ // ^? Pet[]
90
+ const { data: pet } = await usePetStore('/pets/42')
91
+ // ^? Pet
92
+ await usePetStore('/pets', { method: 'post', body: { name: 'Rex' } })
93
+
94
+ await usePetStore('/pats')
95
+ // ^ no GET route matches '/pats'
96
+ await usePetStore('/pets', { method: 'put' })
97
+ // ^ no PUT route matches '/pets'
98
+ await usePetStore('/pets', { method: 'post' })
99
+ // ^ body is required
100
+ ```
101
+
102
+ Only the type of `routes` is read, so pass `{} as Routes`; the value is dropped before the request is
103
+ made. The declared paths are matched **as written**, since they are the paths the API documents. You
104
+ should not prefix them with the `baseURL`. A path built at runtime resolves to `unknown`.
105
+
106
+ ::note
107
+ The routes a client declares are its own. They are not added to your app's route set, so plain
108
+ `$fetch` and `useFetch` are unaffected, and this client will not accept your own server's paths.
109
+ ::
110
+
111
+ ::tip
112
+ The interface above is the shape [`fetchdts`](https://github.com/unjs/fetchdts) uses, which is what
113
+ Nuxt generates for your own server routes. A module can therefore generate one from an API
114
+ description - an OpenAPI document, for example - with `compileRoutes` from `fetchdts/compiler`, and
115
+ hand the emitted interface to `routes`.
116
+ ::
117
+
52
118
  ## Default vs Override Mode
53
119
 
54
120
  ### Default Mode (plain object)
@@ -37,6 +37,13 @@ You do not need to `await` `useFetch`. On the server, Nuxt waits for the promise
37
37
  `data`, `status`, and `error` are Vue refs, and they should be accessed with `.value` when used within the `<script setup>`, while `refresh`/`execute` and `clear` are plain functions.
38
38
  ::
39
39
 
40
+ ::note
41
+ The request URL, the response, and any `body`, `query` or `headers` the matching handler validates
42
+ are typed from the routes your server serves. A path built at runtime resolves to `unknown`, and
43
+ naming the response type (`useFetch<Todo[]>(url)`) overrides whatever Nuxt resolved. Read more about
44
+ [typed routes](/docs/4.x/getting-started/data-fetching#typed-routes).
45
+ ::
46
+
40
47
  Using the `query` option, you can add search parameters to your query. This option is extended from [unjs/ofetch](https://github.com/unjs/ofetch) and is using [unjs/ufo](https://github.com/unjs/ufo) to create the URL. Objects are automatically stringified.
41
48
 
42
49
  ```ts [app/pages/index.vue]
@@ -157,7 +164,6 @@ type UseFetchOptions<ResT, DataT = ResT> = {
157
164
  key?: MaybeRefOrGetter<string>
158
165
  method?: MaybeRefOrGetter<string>
159
166
  query?: MaybeRefOrGetter<SearchParams>
160
- params?: MaybeRefOrGetter<SearchParams>
161
167
  body?: MaybeRefOrGetter<RequestInit['body'] | Record<string, any>>
162
168
  headers?: MaybeRefOrGetter<Record<string, string> | [key: string, value: string][] | Headers>
163
169
  baseURL?: MaybeRefOrGetter<string>
@@ -212,8 +218,7 @@ type AsyncDataRequestStatus = 'idle' | 'pending' | 'success' | 'error'
212
218
  |---------------------------------------------------------------------------|-------------------------------------------------------------------------|------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
213
219
  | `key` | `MaybeRefOrGetter<string>` | auto-gen | Unique key for de-duplication. If not provided, generated from the URL, options and call site location in the source code. |
214
220
  | `method` | `MaybeRefOrGetter<string>` | `'GET'` | HTTP request method. |
215
- | `query` | `MaybeRefOrGetter<SearchParams>` | - | Query/search params to append to the URL. Alias: `params`. |
216
- | `params` | `MaybeRefOrGetter<SearchParams>` | - | Alias for `query`. |
221
+ | `query` | `MaybeRefOrGetter<SearchParams>` | - | Query/search params to append to the URL. |
217
222
  | `body` | `MaybeRefOrGetter<RequestInit['body'] \| Record<string, any>>` | - | Request body. Objects are automatically stringified. |
218
223
  | `headers` | `MaybeRefOrGetter<Record<string, string> \| [key, value][] \| Headers>` | - | Request headers. |
219
224
  | `baseURL` | `MaybeRefOrGetter<string>` | - | Base URL for the request. |
@@ -64,6 +64,18 @@ async function contactForm () {
64
64
  If you use `$fetch` to call an (external) HTTPS URL with a self-signed certificate in development, you will need to set `NODE_TLS_REJECT_UNAUTHORIZED=0` in your environment.
65
65
  ::
66
66
 
67
+ ## Typed Requests
68
+
69
+ `$fetch` is typed from the routes your server serves, so a response is typed by the handler that
70
+ answers it, and a body, query or headers the handler validates are enforced on the call. A path
71
+ built at runtime, an absolute URL or a `Request` object resolves to `unknown`; naming the response
72
+ type (`$fetch<Todo[]>(url)`) overrides whatever Nuxt resolved.
73
+
74
+ ::read-more{to="/docs/4.x/getting-started/data-fetching#typed-routes"}
75
+ Read more about typed routes, including how to declare a route Nuxt cannot see and how to reject a
76
+ path no route answers.
77
+ ::
78
+
67
79
  ### Passing Headers and Cookies
68
80
 
69
81
  When we call `$fetch` in the browser, user headers like `cookie` will be directly sent to the API.
@@ -49,6 +49,7 @@ Check the [schema source code](https://github.com/nuxt/nuxt/blob/main/packages/s
49
49
  | `app:resolve` | `app` | Called after resolving the `app` instance. |
50
50
  | `app:templates` | `app` | Called during `NuxtApp` generation, to allow customizing, modifying or adding new files to the build directory (either virtually or to written to `.nuxt`). |
51
51
  | `app:templatesGenerated` | `app` | Called after templates are compiled into the [virtual file system](/docs/4.x/directory-structure/nuxt) (vfs). |
52
+ | `server:routes` | `routes, context` | Called when Nuxt needs the full set of route handlers the server will serve, so that it can type `$fetch` and `useFetch` against them. The configured server builder adds the handlers it discovered by scanning, alongside those registered through `serverHandlers`. |
52
53
  | `build:before` | - | Called before Nuxt bundle builder. |
53
54
  | `build:done` | - | Called after Nuxt bundle builder is complete. |
54
55
  | `build:manifest` | `manifest` | Called during the manifest build by Vite and webpack. This allows customizing the manifest that Nitro will use to render `<script>` and `<link>` tags in the final HTML. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nuxt/docs-nightly",
3
- "version": "5.0.0-29805604.ff4efc9e",
3
+ "version": "5.0.0-29805621.06b691a8",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/nuxt/nuxt.git",