@nuxt/docs 0.0.0 → 3.17.1

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.
Files changed (224) hide show
  1. package/.navigation.yml +2 -0
  2. package/1.getting-started/.navigation.yml +3 -0
  3. package/1.getting-started/01.introduction.md +81 -0
  4. package/1.getting-started/02.installation.md +109 -0
  5. package/1.getting-started/03.configuration.md +226 -0
  6. package/1.getting-started/04.views.md +163 -0
  7. package/1.getting-started/05.assets.md +48 -0
  8. package/1.getting-started/06.styling.md +565 -0
  9. package/1.getting-started/07.routing.md +149 -0
  10. package/1.getting-started/08.seo-meta.md +360 -0
  11. package/1.getting-started/09.transitions.md +473 -0
  12. package/1.getting-started/10.data-fetching.md +795 -0
  13. package/1.getting-started/11.state-management.md +223 -0
  14. package/1.getting-started/12.error-handling.md +233 -0
  15. package/1.getting-started/13.server.md +94 -0
  16. package/1.getting-started/14.layers.md +92 -0
  17. package/1.getting-started/15.prerendering.md +194 -0
  18. package/1.getting-started/16.deployment.md +130 -0
  19. package/1.getting-started/17.testing.md +728 -0
  20. package/1.getting-started/18.upgrade.md +997 -0
  21. package/2.guide/.navigation.yml +2 -0
  22. package/2.guide/0.index.md +22 -0
  23. package/2.guide/1.concepts/.navigation.yml +3 -0
  24. package/2.guide/1.concepts/1.auto-imports.md +205 -0
  25. package/2.guide/1.concepts/10.nuxt-lifecycle.md +141 -0
  26. package/2.guide/1.concepts/2.vuejs-development.md +103 -0
  27. package/2.guide/1.concepts/3.rendering.md +255 -0
  28. package/2.guide/1.concepts/4.server-engine.md +62 -0
  29. package/2.guide/1.concepts/5.modules.md +48 -0
  30. package/2.guide/1.concepts/7.esm.md +299 -0
  31. package/2.guide/1.concepts/8.typescript.md +97 -0
  32. package/2.guide/1.concepts/9.code-style.md +22 -0
  33. package/2.guide/2.directory-structure/.navigation.yml +3 -0
  34. package/2.guide/2.directory-structure/0.nuxt.md +20 -0
  35. package/2.guide/2.directory-structure/0.output.md +18 -0
  36. package/2.guide/2.directory-structure/1.assets.md +16 -0
  37. package/2.guide/2.directory-structure/1.components.md +608 -0
  38. package/2.guide/2.directory-structure/1.composables.md +121 -0
  39. package/2.guide/2.directory-structure/1.content.md +64 -0
  40. package/2.guide/2.directory-structure/1.layouts.md +180 -0
  41. package/2.guide/2.directory-structure/1.middleware.md +209 -0
  42. package/2.guide/2.directory-structure/1.modules.md +66 -0
  43. package/2.guide/2.directory-structure/1.node_modules.md +12 -0
  44. package/2.guide/2.directory-structure/1.pages.md +440 -0
  45. package/2.guide/2.directory-structure/1.plugins.md +299 -0
  46. package/2.guide/2.directory-structure/1.public.md +27 -0
  47. package/2.guide/2.directory-structure/1.server.md +546 -0
  48. package/2.guide/2.directory-structure/1.shared.md +104 -0
  49. package/2.guide/2.directory-structure/1.utils.md +49 -0
  50. package/2.guide/2.directory-structure/2.env.md +75 -0
  51. package/2.guide/2.directory-structure/2.gitignore.md +37 -0
  52. package/2.guide/2.directory-structure/2.nuxtignore.md +36 -0
  53. package/2.guide/2.directory-structure/2.nuxtrc.md +50 -0
  54. package/2.guide/2.directory-structure/3.app-config.md +177 -0
  55. package/2.guide/2.directory-structure/3.app.md +72 -0
  56. package/2.guide/2.directory-structure/3.error.md +55 -0
  57. package/2.guide/2.directory-structure/3.nuxt-config.md +34 -0
  58. package/2.guide/2.directory-structure/3.package.md +32 -0
  59. package/2.guide/2.directory-structure/3.tsconfig.md +24 -0
  60. package/2.guide/3.going-further/.navigation.yml +3 -0
  61. package/2.guide/3.going-further/1.experimental-features.md +689 -0
  62. package/2.guide/3.going-further/1.features.md +103 -0
  63. package/2.guide/3.going-further/1.internals.md +81 -0
  64. package/2.guide/3.going-further/10.runtime-config.md +174 -0
  65. package/2.guide/3.going-further/11.nightly-release-channel.md +68 -0
  66. package/2.guide/3.going-further/2.hooks.md +98 -0
  67. package/2.guide/3.going-further/3.modules.md +811 -0
  68. package/2.guide/3.going-further/4.kit.md +51 -0
  69. package/2.guide/3.going-further/6.nuxt-app.md +64 -0
  70. package/2.guide/3.going-further/7.layers.md +227 -0
  71. package/2.guide/3.going-further/9.debugging.md +115 -0
  72. package/2.guide/3.going-further/index.md +4 -0
  73. package/2.guide/4.recipes/.navigation.yml +3 -0
  74. package/2.guide/4.recipes/1.custom-routing.md +181 -0
  75. package/2.guide/4.recipes/2.vite-plugin.md +65 -0
  76. package/2.guide/4.recipes/3.custom-usefetch.md +125 -0
  77. package/2.guide/4.recipes/4.sessions-and-authentication.md +203 -0
  78. package/3.api/.navigation.yml +3 -0
  79. package/3.api/1.components/.navigation.yml +3 -0
  80. package/3.api/1.components/1.client-only.md +76 -0
  81. package/3.api/1.components/1.dev-only.md +51 -0
  82. package/3.api/1.components/1.nuxt-client-fallback.md +80 -0
  83. package/3.api/1.components/10.nuxt-picture.md +27 -0
  84. package/3.api/1.components/11.teleports.md +40 -0
  85. package/3.api/1.components/12.nuxt-route-announcer.md +56 -0
  86. package/3.api/1.components/13.nuxt-time.md +173 -0
  87. package/3.api/1.components/2.nuxt-page.md +154 -0
  88. package/3.api/1.components/3.nuxt-layout.md +156 -0
  89. package/3.api/1.components/4.nuxt-link.md +322 -0
  90. package/3.api/1.components/5.nuxt-loading-indicator.md +50 -0
  91. package/3.api/1.components/6.nuxt-error-boundary.md +65 -0
  92. package/3.api/1.components/7.nuxt-welcome.md +25 -0
  93. package/3.api/1.components/8.nuxt-island.md +70 -0
  94. package/3.api/1.components/9.nuxt-img.md +43 -0
  95. package/3.api/2.composables/.navigation.yml +3 -0
  96. package/3.api/2.composables/on-prehydrate.md +60 -0
  97. package/3.api/2.composables/use-app-config.md +19 -0
  98. package/3.api/2.composables/use-async-data.md +212 -0
  99. package/3.api/2.composables/use-cookie.md +233 -0
  100. package/3.api/2.composables/use-error.md +32 -0
  101. package/3.api/2.composables/use-fetch.md +217 -0
  102. package/3.api/2.composables/use-head-safe.md +55 -0
  103. package/3.api/2.composables/use-head.md +69 -0
  104. package/3.api/2.composables/use-hydration.md +68 -0
  105. package/3.api/2.composables/use-lazy-async-data.md +47 -0
  106. package/3.api/2.composables/use-lazy-fetch.md +55 -0
  107. package/3.api/2.composables/use-loading-indicator.md +77 -0
  108. package/3.api/2.composables/use-nuxt-app.md +294 -0
  109. package/3.api/2.composables/use-nuxt-data.md +112 -0
  110. package/3.api/2.composables/use-preview-mode.md +118 -0
  111. package/3.api/2.composables/use-request-event.md +23 -0
  112. package/3.api/2.composables/use-request-fetch.md +52 -0
  113. package/3.api/2.composables/use-request-header.md +34 -0
  114. package/3.api/2.composables/use-request-headers.md +37 -0
  115. package/3.api/2.composables/use-request-url.md +41 -0
  116. package/3.api/2.composables/use-response-header.md +48 -0
  117. package/3.api/2.composables/use-route-announcer.md +60 -0
  118. package/3.api/2.composables/use-route.md +52 -0
  119. package/3.api/2.composables/use-router.md +92 -0
  120. package/3.api/2.composables/use-runtime-config.md +142 -0
  121. package/3.api/2.composables/use-runtime-hook.md +43 -0
  122. package/3.api/2.composables/use-seo-meta.md +80 -0
  123. package/3.api/2.composables/use-server-seo-meta.md +27 -0
  124. package/3.api/2.composables/use-state.md +48 -0
  125. package/3.api/3.utils/$fetch.md +98 -0
  126. package/3.api/3.utils/.navigation.yml +3 -0
  127. package/3.api/3.utils/abort-navigation.md +73 -0
  128. package/3.api/3.utils/add-route-middleware.md +88 -0
  129. package/3.api/3.utils/call-once.md +92 -0
  130. package/3.api/3.utils/clear-error.md +29 -0
  131. package/3.api/3.utils/clear-nuxt-data.md +23 -0
  132. package/3.api/3.utils/clear-nuxt-state.md +23 -0
  133. package/3.api/3.utils/create-error.md +55 -0
  134. package/3.api/3.utils/define-nuxt-component.md +53 -0
  135. package/3.api/3.utils/define-nuxt-route-middleware.md +67 -0
  136. package/3.api/3.utils/define-page-meta.md +234 -0
  137. package/3.api/3.utils/define-route-rules.md +52 -0
  138. package/3.api/3.utils/navigate-to.md +230 -0
  139. package/3.api/3.utils/on-before-route-leave.md +11 -0
  140. package/3.api/3.utils/on-before-route-update.md +11 -0
  141. package/3.api/3.utils/on-nuxt-ready.md +25 -0
  142. package/3.api/3.utils/prefetch-components.md +28 -0
  143. package/3.api/3.utils/preload-components.md +23 -0
  144. package/3.api/3.utils/preload-route-components.md +41 -0
  145. package/3.api/3.utils/prerender-routes.md +46 -0
  146. package/3.api/3.utils/refresh-cookie.md +46 -0
  147. package/3.api/3.utils/refresh-nuxt-data.md +91 -0
  148. package/3.api/3.utils/reload-nuxt-app.md +74 -0
  149. package/3.api/3.utils/set-page-layout.md +24 -0
  150. package/3.api/3.utils/set-response-status.md +36 -0
  151. package/3.api/3.utils/show-error.md +31 -0
  152. package/3.api/3.utils/update-app-config.md +27 -0
  153. package/3.api/4.commands/.navigation.yml +3 -0
  154. package/3.api/4.commands/add.md +112 -0
  155. package/3.api/4.commands/analyze.md +41 -0
  156. package/3.api/4.commands/build-module.md +42 -0
  157. package/3.api/4.commands/build.md +46 -0
  158. package/3.api/4.commands/cleanup.md +38 -0
  159. package/3.api/4.commands/dev.md +59 -0
  160. package/3.api/4.commands/devtools.md +38 -0
  161. package/3.api/4.commands/generate.md +41 -0
  162. package/3.api/4.commands/info.md +33 -0
  163. package/3.api/4.commands/init.md +46 -0
  164. package/3.api/4.commands/module.md +84 -0
  165. package/3.api/4.commands/prepare.md +36 -0
  166. package/3.api/4.commands/preview.md +43 -0
  167. package/3.api/4.commands/typecheck.md +42 -0
  168. package/3.api/4.commands/upgrade.md +37 -0
  169. package/3.api/5.kit/.navigation.yml +3 -0
  170. package/3.api/5.kit/1.modules.md +172 -0
  171. package/3.api/5.kit/10.runtime-config.md +27 -0
  172. package/3.api/5.kit/10.templates.md +283 -0
  173. package/3.api/5.kit/11.nitro.md +409 -0
  174. package/3.api/5.kit/12.resolving.md +268 -0
  175. package/3.api/5.kit/13.logging.md +65 -0
  176. package/3.api/5.kit/14.builder.md +491 -0
  177. package/3.api/5.kit/15.examples.md +41 -0
  178. package/3.api/5.kit/2.programmatic.md +125 -0
  179. package/3.api/5.kit/3.compatibility.md +230 -0
  180. package/3.api/5.kit/4.autoimports.md +144 -0
  181. package/3.api/5.kit/5.components.md +127 -0
  182. package/3.api/5.kit/6.context.md +130 -0
  183. package/3.api/5.kit/7.pages.md +295 -0
  184. package/3.api/5.kit/8.layout.md +80 -0
  185. package/3.api/5.kit/9.plugins.md +263 -0
  186. package/3.api/6.advanced/.navigation.yml +1 -0
  187. package/3.api/6.advanced/1.hooks.md +105 -0
  188. package/3.api/6.advanced/2.import-meta.md +60 -0
  189. package/3.api/6.nuxt-config.md +12 -0
  190. package/3.api/index.md +31 -0
  191. package/5.community/.navigation.yml +3 -0
  192. package/5.community/2.getting-help.md +48 -0
  193. package/5.community/3.reporting-bugs.md +50 -0
  194. package/5.community/4.contribution.md +205 -0
  195. package/5.community/5.framework-contribution.md +142 -0
  196. package/5.community/6.roadmap.md +79 -0
  197. package/5.community/7.changelog.md +92 -0
  198. package/6.bridge/.navigation.yml +3 -0
  199. package/6.bridge/1.overview.md +137 -0
  200. package/6.bridge/10.configuration.md +96 -0
  201. package/6.bridge/2.typescript.md +46 -0
  202. package/6.bridge/3.bridge-composition-api.md +132 -0
  203. package/6.bridge/4.plugins-and-middleware.md +65 -0
  204. package/6.bridge/5.nuxt3-compatible-api.md +204 -0
  205. package/6.bridge/6.meta.md +117 -0
  206. package/6.bridge/7.runtime-config.md +38 -0
  207. package/6.bridge/8.nitro.md +102 -0
  208. package/6.bridge/9.vite.md +37 -0
  209. package/7.migration/.navigation.yml +3 -0
  210. package/7.migration/1.overview.md +24 -0
  211. package/7.migration/10.bundling.md +28 -0
  212. package/7.migration/11.server.md +17 -0
  213. package/7.migration/2.configuration.md +240 -0
  214. package/7.migration/20.module-authors.md +94 -0
  215. package/7.migration/3.auto-imports.md +18 -0
  216. package/7.migration/4.meta.md +127 -0
  217. package/7.migration/5.plugins-and-middleware.md +80 -0
  218. package/7.migration/6.pages-and-layouts.md +233 -0
  219. package/7.migration/7.component-options.md +156 -0
  220. package/7.migration/8.runtime-config.md +58 -0
  221. package/LICENSE +21 -0
  222. package/README.md +11 -0
  223. package/package.json +16 -4
  224. package/dist/.gitkeep +0 -0
@@ -0,0 +1,546 @@
1
+ ---
2
+ title: server
3
+ head.title: 'server/'
4
+ description: The server/ directory is used to register API and server handlers to your application.
5
+ navigation.icon: i-lucide-folder
6
+ ---
7
+
8
+ Nuxt automatically scans files inside these directories to register API and server handlers with Hot Module Replacement (HMR) support.
9
+
10
+ ```bash [Directory structure]
11
+ -| server/
12
+ ---| api/
13
+ -----| hello.ts # /api/hello
14
+ ---| routes/
15
+ -----| bonjour.ts # /bonjour
16
+ ---| middleware/
17
+ -----| log.ts # log all requests
18
+ ```
19
+
20
+ Each file should export a default function defined with `defineEventHandler()` or `eventHandler()` (alias).
21
+
22
+ The handler can directly return JSON data, a `Promise`, or use `event.node.res.end()` to send a response.
23
+
24
+ ```ts twoslash [server/api/hello.ts]
25
+ export default defineEventHandler((event) => {
26
+ return {
27
+ hello: 'world'
28
+ }
29
+ })
30
+ ```
31
+
32
+ You can now universally call this API in your pages and components:
33
+
34
+ ```vue [pages/index.vue]
35
+ <script setup lang="ts">
36
+ const { data } = await useFetch('/api/hello')
37
+ </script>
38
+
39
+ <template>
40
+ <pre>{{ data }}</pre>
41
+ </template>
42
+ ```
43
+
44
+ ## Server Routes
45
+
46
+ Files inside the `~/server/api` are automatically prefixed with `/api` in their route.
47
+
48
+ :video-accordion{title="Watch a video from Vue School on API routes" videoId="761468863" platform="vimeo"}
49
+
50
+ To add server routes without `/api` prefix, put them into `~/server/routes` directory.
51
+
52
+ **Example:**
53
+
54
+ ```ts [server/routes/hello.ts]
55
+ export default defineEventHandler(() => 'Hello World!')
56
+ ```
57
+
58
+ Given the example above, the `/hello` route will be accessible at <http://localhost:3000/hello>.
59
+
60
+ ::note
61
+ Note that currently server routes do not support the full functionality of dynamic routes as [pages](/docs/guide/directory-structure/pages#dynamic-routes) do.
62
+ ::
63
+
64
+ ## Server Middleware
65
+
66
+ Nuxt will automatically read in any file in the `~/server/middleware` to create server middleware for your project.
67
+
68
+ Middleware handlers will run on every request before any other server route to add or check headers, log requests, or extend the event's request object.
69
+
70
+ ::note
71
+ Middleware handlers should not return anything (nor close or respond to the request) and only inspect or extend the request context or throw an error.
72
+ ::
73
+
74
+ **Examples:**
75
+
76
+ ```ts [server/middleware/log.ts]
77
+ export default defineEventHandler((event) => {
78
+ console.log('New request: ' + getRequestURL(event))
79
+ })
80
+ ```
81
+
82
+ ```ts [server/middleware/auth.ts]
83
+ export default defineEventHandler((event) => {
84
+ event.context.auth = { user: 123 }
85
+ })
86
+ ```
87
+
88
+ ## Server Plugins
89
+
90
+ Nuxt will automatically read any files in the `~/server/plugins` directory and register them as Nitro plugins. This allows extending Nitro's runtime behavior and hooking into lifecycle events.
91
+
92
+ **Example:**
93
+
94
+ ```ts [server/plugins/nitroPlugin.ts]
95
+ export default defineNitroPlugin((nitroApp) => {
96
+ console.log('Nitro plugin', nitroApp)
97
+ })
98
+ ```
99
+
100
+ :read-more{to="https://nitro.unjs.io/guide/plugins" title="Nitro Plugins" target="_blank"}
101
+
102
+ ## Server Utilities
103
+
104
+ Server routes are powered by [unjs/h3](https://github.com/unjs/h3) which comes with a handy set of helpers.
105
+
106
+ :read-more{to="https://www.jsdocs.io/package/h3#package-index-functions" title="Available H3 Request Helpers" target="_blank"}
107
+
108
+ You can add more helpers yourself inside the `~/server/utils` directory.
109
+
110
+ For example, you can define a custom handler utility that wraps the original handler and performs additional operations before returning the final response.
111
+
112
+ **Example:**
113
+
114
+ ```ts [server/utils/handler.ts]
115
+ import type { EventHandler, EventHandlerRequest } from 'h3'
116
+
117
+ export const defineWrappedResponseHandler = <T extends EventHandlerRequest, D> (
118
+ handler: EventHandler<T, D>
119
+ ): EventHandler<T, D> =>
120
+ defineEventHandler<T>(async event => {
121
+ try {
122
+ // do something before the route handler
123
+ const response = await handler(event)
124
+ // do something after the route handler
125
+ return { response }
126
+ } catch (err) {
127
+ // Error handling
128
+ return { err }
129
+ }
130
+ })
131
+ ```
132
+
133
+ ## Server Types
134
+
135
+ ::tip
136
+ This feature is available from Nuxt >= 3.5
137
+ ::
138
+
139
+ To improve clarity within your IDE between the auto-imports from 'nitro' and 'vue', you can add a `~/server/tsconfig.json` with the following content:
140
+
141
+ ```json [server/tsconfig.json]
142
+ {
143
+ "extends": "../.nuxt/tsconfig.server.json"
144
+ }
145
+ ```
146
+
147
+ Currently, these values won't be respected when type checking ([`nuxi typecheck`](/docs/api/commands/typecheck)), but you should get better type hints in your IDE.
148
+
149
+ ## Recipes
150
+
151
+ ### Route Parameters
152
+
153
+ Server routes can use dynamic parameters within brackets in the file name like `/api/hello/[name].ts` and be accessed via `event.context.params`.
154
+
155
+ ```ts [server/api/hello/[name\\].ts]
156
+ export default defineEventHandler((event) => {
157
+ const name = getRouterParam(event, 'name')
158
+
159
+ return `Hello, ${name}!`
160
+ })
161
+ ```
162
+
163
+ ::tip{to="https://h3.unjs.io/examples/validate-data#validate-params"}
164
+ Alternatively, use `getValidatedRouterParams` with a schema validator such as Zod for runtime and type safety.
165
+ ::
166
+
167
+ You can now universally call this API on `/api/hello/nuxt` and get `Hello, nuxt!`.
168
+
169
+ ### Matching HTTP Method
170
+
171
+ Handle file names can be suffixed with `.get`, `.post`, `.put`, `.delete`, ... to match request's [HTTP Method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods).
172
+
173
+ ```ts [server/api/test.get.ts]
174
+ export default defineEventHandler(() => 'Test get handler')
175
+ ```
176
+
177
+ ```ts [server/api/test.post.ts]
178
+ export default defineEventHandler(() => 'Test post handler')
179
+ ```
180
+
181
+ Given the example above, fetching `/test` with:
182
+
183
+ - **GET** method: Returns `Test get handler`
184
+ - **POST** method: Returns `Test post handler`
185
+ - Any other method: Returns 405 error
186
+
187
+ You can also use `index.[method].ts` inside a directory for structuring your code differently, this is useful to create API namespaces.
188
+
189
+ ::code-group
190
+ ```ts [server/api/foo/index.get.ts]
191
+ export default defineEventHandler((event) => {
192
+ // handle GET requests for the `api/foo` endpoint
193
+ })
194
+ ```
195
+ ```ts [server/api/foo/index.post.ts]
196
+ export default defineEventHandler((event) => {
197
+ // handle POST requests for the `api/foo` endpoint
198
+ })
199
+ ```
200
+ ```ts [server/api/foo/bar.get.ts]
201
+ export default defineEventHandler((event) => {
202
+ // handle GET requests for the `api/foo/bar` endpoint
203
+ })
204
+ ```
205
+ ::
206
+
207
+ ### Catch-all Route
208
+
209
+ Catch-all routes are helpful for fallback route handling.
210
+
211
+ For example, creating a file named `~/server/api/foo/[...].ts` will register a catch-all route for all requests that do not match any route handler, such as `/api/foo/bar/baz`.
212
+
213
+ ```ts [server/api/foo/[...\\].ts]
214
+ export default defineEventHandler((event) => {
215
+ // event.context.path to get the route path: '/api/foo/bar/baz'
216
+ // event.context.params._ to get the route segment: 'bar/baz'
217
+ return `Default foo handler`
218
+ })
219
+ ```
220
+
221
+ You can set a name for the catch-all route by using `~/server/api/foo/[...slug].ts` and access it via `event.context.params.slug`.
222
+
223
+ ```ts [server/api/foo/[...slug\\].ts]
224
+ export default defineEventHandler((event) => {
225
+ // event.context.params.slug to get the route segment: 'bar/baz'
226
+ return `Default foo handler`
227
+ })
228
+ ```
229
+
230
+ ### Body Handling
231
+
232
+ ```ts [server/api/submit.post.ts]
233
+ export default defineEventHandler(async (event) => {
234
+ const body = await readBody(event)
235
+ return { body }
236
+ })
237
+ ```
238
+
239
+ ::tip{to="https://unjs.io/blog/2023-08-15-h3-towards-the-edge-of-the-web#runtime-type-safe-request-utils"}
240
+ Alternatively, use `readValidatedBody` with a schema validator such as Zod for runtime and type safety.
241
+ ::
242
+
243
+ You can now universally call this API using:
244
+
245
+ ```vue [app.vue]
246
+ <script setup lang="ts">
247
+ async function submit() {
248
+ const { body } = await $fetch('/api/submit', {
249
+ method: 'post',
250
+ body: { test: 123 }
251
+ })
252
+ }
253
+ </script>
254
+ ```
255
+
256
+ ::note
257
+ We are using `submit.post.ts` in the filename only to match requests with `POST` method that can accept the request body. When using `readBody` within a GET request, `readBody` will throw a `405 Method Not Allowed` HTTP error.
258
+ ::
259
+
260
+ ### Query Parameters
261
+
262
+ Sample query `/api/query?foo=bar&baz=qux`
263
+
264
+ ```ts [server/api/query.get.ts]
265
+ export default defineEventHandler((event) => {
266
+ const query = getQuery(event)
267
+
268
+ return { a: query.foo, b: query.baz }
269
+ })
270
+ ```
271
+
272
+ ::tip{to="https://unjs.io/blog/2023-08-15-h3-towards-the-edge-of-the-web#runtime-type-safe-request-utils"}
273
+ Alternatively, use `getValidatedQuery` with a schema validator such as Zod for runtime and type safety.
274
+ ::
275
+
276
+ ### Error Handling
277
+
278
+ If no errors are thrown, a status code of `200 OK` will be returned.
279
+
280
+ Any uncaught errors will return a `500 Internal Server Error` HTTP Error.
281
+
282
+ To return other error codes, throw an exception with [`createError`](/docs/api/utils/create-error):
283
+
284
+ ```ts [server/api/validation/[id\\].ts]
285
+ export default defineEventHandler((event) => {
286
+ const id = parseInt(event.context.params.id) as number
287
+
288
+ if (!Number.isInteger(id)) {
289
+ throw createError({
290
+ statusCode: 400,
291
+ statusMessage: 'ID should be an integer',
292
+ })
293
+ }
294
+ return 'All good'
295
+ })
296
+ ```
297
+
298
+ ### Status Codes
299
+
300
+ To return other status codes, use the [`setResponseStatus`](/docs/api/utils/set-response-status) utility.
301
+
302
+ For example, to return `202 Accepted`
303
+
304
+ ```ts [server/api/validation/[id\\].ts]
305
+ export default defineEventHandler((event) => {
306
+ setResponseStatus(event, 202)
307
+ })
308
+ ```
309
+
310
+ ### Runtime Config
311
+
312
+ ::code-group
313
+ ```ts [server/api/foo.ts]
314
+ export default defineEventHandler(async (event) => {
315
+ const config = useRuntimeConfig(event)
316
+
317
+ const repo = await $fetch('https://api.github.com/repos/nuxt/nuxt', {
318
+ headers: {
319
+ Authorization: `token ${config.githubToken}`
320
+ }
321
+ })
322
+
323
+ return repo
324
+ })
325
+ ```
326
+ ```ts [nuxt.config.ts]
327
+ export default defineNuxtConfig({
328
+ runtimeConfig: {
329
+ githubToken: ''
330
+ }
331
+ })
332
+ ```
333
+ ```ini [.env]
334
+ NUXT_GITHUB_TOKEN='<my-super-token>'
335
+ ```
336
+ ::
337
+
338
+ ::note
339
+ Giving the `event` as argument to `useRuntimeConfig` is optional, but it is recommended to pass it to get the runtime config overwritten by [environment variables](/docs/guide/going-further/runtime-config#environment-variables) at runtime for server routes.
340
+ ::
341
+
342
+ ### Request Cookies
343
+
344
+ ```ts [server/api/cookies.ts]
345
+ export default defineEventHandler((event) => {
346
+ const cookies = parseCookies(event)
347
+
348
+ return { cookies }
349
+ })
350
+ ```
351
+
352
+ ### Forwarding Context & Headers
353
+
354
+ By default, neither the headers from the incoming request nor the request context are forwarded when
355
+ making fetch requests in server routes. You can use `event.$fetch` to forward the request context and headers when making fetch requests in server routes.
356
+
357
+ ```ts [server/api/forward.ts]
358
+ export default defineEventHandler((event) => {
359
+ return event.$fetch('/api/forwarded')
360
+ })
361
+ ```
362
+
363
+ ::note
364
+ Headers that are **not meant to be forwarded** will **not be included** in the request. These headers include, for example:
365
+ `transfer-encoding`, `connection`, `keep-alive`, `upgrade`, `expect`, `host`, `accept`
366
+ ::
367
+
368
+ ### Awaiting Promises After Response
369
+
370
+ When handling server requests, you might need to perform asynchronous tasks that shouldn't block the response to the client (for example, caching and logging). You can use `event.waitUntil` to await a promise in the background without delaying the response.
371
+
372
+ The `event.waitUntil` method accepts a promise that will be awaited before the handler terminates, ensuring the task is completed even if the server would otherwise terminate the handler right after the response is sent. This integrates with runtime providers to leverage their native capabilities for handling asynchronous operations after the response is sent.
373
+
374
+ ```ts [server/api/background-task.ts]
375
+ const timeConsumingBackgroundTask = async () => {
376
+ await new Promise((resolve) => setTimeout(resolve, 1000))
377
+ };
378
+
379
+ export default eventHandler((event) => {
380
+ // schedule a background task without blocking the response
381
+ event.waitUntil(timeConsumingBackgroundTask())
382
+
383
+ // immediately send the response to the client
384
+ return 'done'
385
+ });
386
+ ```
387
+
388
+ ## Advanced Usage
389
+
390
+ ### Nitro Config
391
+
392
+ You can use `nitro` key in `nuxt.config` to directly set [Nitro configuration](https://nitro.unjs.io/config).
393
+
394
+ ::warning
395
+ This is an advanced option. Custom config can affect production deployments, as the configuration interface might change over time when Nitro is upgraded in semver-minor versions of Nuxt.
396
+ ::
397
+
398
+ ```ts [nuxt.config.ts]
399
+ export default defineNuxtConfig({
400
+ // https://nitro.unjs.io/config
401
+ nitro: {}
402
+ })
403
+ ```
404
+
405
+ :read-more{to="/docs/guide/concepts/server-engine"}
406
+
407
+ ### Nested Router
408
+
409
+ ```ts [server/api/hello/[...slug\\].ts]
410
+ import { createRouter, defineEventHandler, useBase } from 'h3'
411
+
412
+ const router = createRouter()
413
+
414
+ router.get('/test', defineEventHandler(() => 'Hello World'))
415
+
416
+ export default useBase('/api/hello', router.handler)
417
+ ```
418
+
419
+ ### Sending Streams
420
+
421
+ ::tip
422
+ This is an experimental feature and is available in all environments.
423
+ ::
424
+
425
+ ```ts [server/api/foo.get.ts]
426
+ import fs from 'node:fs'
427
+ import { sendStream } from 'h3'
428
+
429
+ export default defineEventHandler((event) => {
430
+ return sendStream(event, fs.createReadStream('/path/to/file'))
431
+ })
432
+ ```
433
+
434
+ ### Sending Redirect
435
+
436
+ ```ts [server/api/foo.get.ts]
437
+ export default defineEventHandler(async (event) => {
438
+ await sendRedirect(event, '/path/redirect/to', 302)
439
+ })
440
+ ```
441
+
442
+ ### Legacy Handler or Middleware
443
+
444
+ ```ts [server/api/legacy.ts]
445
+ export default fromNodeMiddleware((req, res) => {
446
+ res.end('Legacy handler')
447
+ })
448
+ ```
449
+
450
+ ::important
451
+ Legacy support is possible using [unjs/h3](https://github.com/unjs/h3), but it is advised to avoid legacy handlers as much as you can.
452
+ ::
453
+
454
+ ```ts [server/middleware/legacy.ts]
455
+ export default fromNodeMiddleware((req, res, next) => {
456
+ console.log('Legacy middleware')
457
+ next()
458
+ })
459
+ ```
460
+
461
+ ::warning
462
+ Never combine `next()` callback with a legacy middleware that is `async` or returns a `Promise`.
463
+ ::
464
+
465
+ ### Server Storage
466
+
467
+ Nitro provides a cross-platform [storage layer](https://nitro.unjs.io/guide/storage). In order to configure additional storage mount points, you can use `nitro.storage`, or [server plugins](#server-plugins).
468
+
469
+ **Example of adding a Redis storage:**
470
+
471
+ Using `nitro.storage`:
472
+
473
+ ```ts [nuxt.config.ts]
474
+ export default defineNuxtConfig({
475
+ nitro: {
476
+ storage: {
477
+ redis: {
478
+ driver: 'redis',
479
+ /* redis connector options */
480
+ port: 6379, // Redis port
481
+ host: "127.0.0.1", // Redis host
482
+ username: "", // needs Redis >= 6
483
+ password: "",
484
+ db: 0, // Defaults to 0
485
+ tls: {} // tls/ssl
486
+ }
487
+ }
488
+ }
489
+ })
490
+ ```
491
+
492
+ Then in your API handler:
493
+
494
+ ```ts [server/api/storage/test.ts]
495
+ export default defineEventHandler(async (event) => {
496
+ // List all keys with
497
+ const keys = await useStorage('redis').getKeys()
498
+
499
+ // Set a key with
500
+ await useStorage('redis').setItem('foo', 'bar')
501
+
502
+ // Remove a key with
503
+ await useStorage('redis').removeItem('foo')
504
+
505
+ return {}
506
+ })
507
+ ```
508
+
509
+ ::read-more{to="https://nitro.unjs.io/guide/storage" target="_blank"}
510
+ Read more about Nitro Storage Layer.
511
+ ::
512
+
513
+ Alternatively, you can create a storage mount point using a server plugin and runtime config:
514
+
515
+ ::code-group
516
+ ```ts [server/plugins/storage.ts]
517
+ import redisDriver from 'unstorage/drivers/redis'
518
+
519
+ export default defineNitroPlugin(() => {
520
+ const storage = useStorage()
521
+
522
+ // Dynamically pass in credentials from runtime configuration, or other sources
523
+ const driver = redisDriver({
524
+ base: 'redis',
525
+ host: useRuntimeConfig().redis.host,
526
+ port: useRuntimeConfig().redis.port,
527
+ /* other redis connector options */
528
+ })
529
+
530
+ // Mount driver
531
+ storage.mount('redis', driver)
532
+ })
533
+ ```
534
+
535
+ ``` ts [nuxt.config.ts]
536
+ export default defineNuxtConfig({
537
+ runtimeConfig: {
538
+ redis: { // Default values
539
+ host: '',
540
+ port: 0,
541
+ /* other redis connector options */
542
+ }
543
+ }
544
+ })
545
+ ```
546
+ ::
@@ -0,0 +1,104 @@
1
+ ---
2
+ title: 'shared'
3
+ head.title: 'shared/'
4
+ description: 'Use the shared/ directory to share functionality between the Vue app and the Nitro server.'
5
+ navigation.icon: i-lucide-folder
6
+ ---
7
+
8
+ The `shared/` directory allows you to share code that can be used in both the Vue app and the Nitro server.
9
+
10
+ ::note
11
+ The `shared/` directory is available in Nuxt v3.14+.
12
+ ::
13
+
14
+ ::important
15
+ Code in the `shared/` directory cannot import any Vue or Nitro code.
16
+ ::
17
+
18
+ ::warning
19
+ Auto-imports are not enabled by default in Nuxt v3 to prevent breaking changes in existing projects.
20
+
21
+ To use these auto-imported utils and types, you must first [set `future.compatibilityVersion: 4` in your `nuxt.config.ts`](/docs/getting-started/upgrade#opting-in-to-nuxt-4).
22
+ ::
23
+
24
+ :video-accordion{title="Watch a video from Vue School on sharing utils and types between app and server" videoId="nnAR-MO3q5M"}
25
+
26
+ ## Usage
27
+
28
+ **Method 1:** Named export
29
+
30
+ ```ts twoslash [shared/utils/capitalize.ts]
31
+ export const capitalize = (input: string) => {
32
+ return input[0] ? input[0].toUpperCase() + input.slice(1) : ''
33
+ }
34
+ ```
35
+
36
+ **Method 2:** Default export
37
+
38
+ ```ts twoslash [shared/utils/capitalize.ts]
39
+ export default function (input: string) {
40
+ return input[0] ? input[0].toUpperCase() + input.slice(1) : ''
41
+ }
42
+ ```
43
+
44
+ You can now use [auto-imported](/docs/guide/directory-structure/shared#auto-imports) utilities in your Nuxt app and `server/` directory.
45
+
46
+ ```vue [app.vue]
47
+ <script setup lang="ts">
48
+ const hello = capitalize('hello')
49
+ </script>
50
+
51
+ <template>
52
+ <div>
53
+ {{ hello }}
54
+ </div>
55
+ </template>
56
+ ```
57
+
58
+ ```ts [server/api/hello.get.ts]
59
+ export default defineEventHandler((event) => {
60
+ return {
61
+ hello: capitalize('hello')
62
+ }
63
+ })
64
+ ```
65
+
66
+ ## How Files Are Scanned
67
+
68
+ Only files in the `shared/utils/` and `shared/types/` directories will be auto-imported. Files nested within subdirectories of these directories will not be auto-imported unless you add these directories to `imports.dirs` and `nitro.imports.dirs`.
69
+
70
+ ::tip
71
+ The way `shared/utils` and `shared/types` auto-imports work and are scanned is identical to the [`composables/`](/docs/guide/directory-structure/composables) and [`utils/`](/docs/guide/directory-structure/utils) directories.
72
+ ::
73
+
74
+ :read-more{to="/docs/guide/directory-structure/composables#how-files-are-scanned"}
75
+
76
+ ```bash [Directory Structure]
77
+ -| shared/
78
+ ---| capitalize.ts # Not auto-imported
79
+ ---| formatters
80
+ -----| lower.ts # Not auto-imported
81
+ ---| utils/
82
+ -----| lower.ts # Auto-imported
83
+ -----| formatters
84
+ -------| upper.ts # Not auto-imported
85
+ ---| types/
86
+ -----| bar.d.ts # Auto-imported
87
+ ```
88
+
89
+ Any other files you create in the `shared/` folder must be manually imported using the `#shared` alias (automatically configured by Nuxt):
90
+
91
+ ```ts
92
+ // For files directly in the shared directory
93
+ import capitalize from '#shared/capitalize'
94
+
95
+ // For files in nested directories
96
+ import lower from '#shared/formatters/lower'
97
+
98
+ // For files nested in a folder within utils
99
+ import upper from '#shared/utils/formatters/upper'
100
+ ```
101
+
102
+ This alias ensures consistent imports across your application, regardless of the importing file's location.
103
+
104
+ :read-more{to="/docs/guide/concepts/auto-imports"}
@@ -0,0 +1,49 @@
1
+ ---
2
+ title: 'utils'
3
+ head.title: 'utils/'
4
+ description: Use the utils/ directory to auto-import your utility functions throughout your application.
5
+ navigation.icon: i-lucide-folder
6
+ ---
7
+
8
+ The main purpose of the [`utils/` directory](/docs/guide/directory-structure/utils) is to allow a semantic distinction between your Vue composables and other auto-imported utility functions.
9
+
10
+ ## Usage
11
+
12
+ **Method 1:** Using named export
13
+
14
+ ```ts twoslash [utils/index.ts]
15
+ export const { format: formatNumber } = Intl.NumberFormat('en-GB', {
16
+ notation: 'compact',
17
+ maximumFractionDigits: 1
18
+ })
19
+ ```
20
+
21
+ **Method 2:** Using default export
22
+
23
+ ```ts twoslash [utils/random-entry.ts or utils/randomEntry.ts]
24
+ // It will be available as randomEntry() (camelCase of file name without extension)
25
+ export default function (arr: Array<any>) {
26
+ return arr[Math.floor(Math.random() * arr.length)]
27
+ }
28
+ ```
29
+
30
+ You can now use auto imported utility functions in `.js`, `.ts` and `.vue` files
31
+
32
+ ```vue [app.vue]
33
+ <template>
34
+ <p>{{ formatNumber(1234) }}</p>
35
+ </template>
36
+ ```
37
+
38
+ :read-more{to="/docs/guide/concepts/auto-imports"}
39
+
40
+ :link-example{to="/docs/examples/features/auto-imports"}
41
+
42
+ ::tip
43
+ The way `utils/` auto-imports work and are scanned is identical to the [`composables/`](/docs/guide/directory-structure/composables) directory.
44
+ ::
45
+
46
+ ::important
47
+ These utils are only available within the Vue part of your app. :br
48
+ Only `server/utils` are auto-imported in the [`server/`](/docs/guide/directory-structure/server#server-utilities) directory.
49
+ ::