nitro 3.0.1-alpha.2 → 3.0.260415-beta

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 (297) hide show
  1. package/LICENSE +6 -0
  2. package/README.md +2 -2
  3. package/dist/THIRD-PARTY-LICENSES.md +1646 -0
  4. package/dist/_build/common.mjs +7261 -3812
  5. package/dist/_build/rolldown.mjs +32 -42
  6. package/dist/_build/rollup.mjs +28 -48
  7. package/dist/_build/vite.build.mjs +10 -10
  8. package/dist/_chunks/nitro.mjs +102 -327
  9. package/dist/_chunks/nitro2.mjs +8 -9
  10. package/dist/_chunks/nitro3.mjs +136 -0
  11. package/dist/_chunks/nitro4.mjs +127 -0
  12. package/dist/_chunks/utils.mjs +40 -29
  13. package/dist/_common.mjs +13 -25
  14. package/dist/_dev.d.mts +0 -3
  15. package/dist/{_chunks/dev.mjs → _dev.mjs} +132 -330
  16. package/dist/_libs/_.mjs +2 -0
  17. package/dist/_libs/_2.mjs +2 -0
  18. package/dist/_libs/_3.mjs +2 -0
  19. package/dist/_libs/_4.mjs +2 -0
  20. package/dist/_libs/_5.mjs +2 -0
  21. package/dist/_libs/_6.mjs +2 -0
  22. package/dist/_libs/_7.mjs +2 -0
  23. package/dist/_libs/c12+rc9.mjs +814 -0
  24. package/dist/_libs/{c12+giget+readdirp+chokidar.d.mts → c12+readdirp+chokidar.d.mts} +49 -40
  25. package/dist/_libs/citty.mjs +142 -41
  26. package/dist/_libs/commondir+is-reference.mjs +60 -56
  27. package/dist/_libs/compatx.d.mts +0 -2
  28. package/dist/_libs/compatx.mjs +1 -4
  29. package/dist/_libs/esbuild.d.mts +0 -1
  30. package/dist/_libs/escape-string-regexp.mjs +1 -4
  31. package/dist/_libs/{pluginutils+plugin-commonjs.d.mts → estree+pluginutils.d.mts} +0 -5
  32. package/dist/_libs/estree-walker.mjs +4 -92
  33. package/dist/_libs/exsolve.d.mts +1 -0
  34. package/dist/_libs/hasown+resolve+deepmerge.mjs +160 -246
  35. package/dist/_libs/httpxy.d.mts +20 -13
  36. package/dist/_libs/httpxy.mjs +519 -95
  37. package/dist/_libs/js-tokens.d.mts +1 -0
  38. package/dist/_libs/klona.mjs +1 -4
  39. package/dist/_libs/magic-string.d.mts +0 -2
  40. package/dist/_libs/mlly.d.mts +0 -2
  41. package/dist/_libs/nypm+tinyexec.mjs +822 -0
  42. package/dist/_libs/perfect-debounce.mjs +68 -0
  43. package/dist/_libs/pkg-types.d.mts +0 -3
  44. package/dist/_libs/plugin-alias.mjs +1 -5
  45. package/dist/_libs/plugin-inject.mjs +1 -7
  46. package/dist/_libs/plugin-json.mjs +1 -5
  47. package/dist/_libs/pluginutils.mjs +3 -35
  48. package/dist/_libs/readdirp+chokidar.mjs +187 -365
  49. package/dist/_libs/remapping.mjs +1 -5
  50. package/dist/_libs/resolve-uri+gen-mapping.mjs +15 -53
  51. package/dist/_libs/rou3.d.mts +1 -4
  52. package/dist/_libs/rou3.mjs +223 -78
  53. package/dist/_libs/std-env.d.mts +8 -2
  54. package/dist/_libs/strip-literal.d.mts +1 -0
  55. package/dist/_libs/tsconfck.mjs +21 -334
  56. package/dist/_libs/ultrahtml.mjs +3 -16
  57. package/dist/_libs/unimport+unplugin.mjs +244 -388
  58. package/dist/_libs/unplugin+unimport.d.mts +5 -15
  59. package/dist/_libs/unwasm.d.mts +0 -3
  60. package/dist/_presets.mjs +576 -488
  61. package/dist/builder.d.mts +5 -25
  62. package/dist/builder.mjs +3 -8
  63. package/dist/cli/_chunks/build.mjs +22 -25
  64. package/dist/cli/_chunks/common.mjs +1 -4
  65. package/dist/cli/_chunks/deploy.mjs +37 -0
  66. package/dist/cli/_chunks/dev.mjs +6 -11
  67. package/dist/cli/_chunks/docs.mjs +28 -0
  68. package/dist/cli/_chunks/list.mjs +4 -8
  69. package/dist/cli/_chunks/prepare.mjs +2 -6
  70. package/dist/cli/_chunks/preview.mjs +48 -0
  71. package/dist/cli/_chunks/run.mjs +7 -11
  72. package/dist/cli/_chunks/task.mjs +1 -5
  73. package/dist/cli/index.mjs +5 -6
  74. package/dist/docs/0.docs/0.index/index.md +56 -0
  75. package/dist/docs/0.docs/1.quick-start.md +110 -0
  76. package/dist/docs/0.docs/10.lifecycle.md +204 -0
  77. package/dist/docs/0.docs/11.openapi.md +291 -0
  78. package/dist/docs/0.docs/12.plugins.md +164 -0
  79. package/dist/docs/0.docs/13.tasks.md +277 -0
  80. package/dist/docs/0.docs/14.websocket.md +386 -0
  81. package/dist/docs/0.docs/15.migration.md +213 -0
  82. package/dist/docs/0.docs/16.nightly.md +31 -0
  83. package/dist/docs/0.docs/2.renderer.md +322 -0
  84. package/dist/docs/0.docs/3.routing.md +711 -0
  85. package/dist/docs/0.docs/4.server-entry.md +239 -0
  86. package/dist/docs/0.docs/5.cache.md +408 -0
  87. package/dist/docs/0.docs/6.storage.md +261 -0
  88. package/dist/docs/0.docs/7.assets.md +166 -0
  89. package/dist/docs/0.docs/8.configuration.md +256 -0
  90. package/dist/docs/0.docs/9.database.md +185 -0
  91. package/dist/docs/1.deploy/0.index/index.md +64 -0
  92. package/dist/docs/1.deploy/1.runtimes/0.node.md +63 -0
  93. package/dist/docs/1.deploy/1.runtimes/1.bun.md +15 -0
  94. package/dist/docs/1.deploy/1.runtimes/2.deno.md +19 -0
  95. package/dist/docs/1.deploy/2.providers/0.alwaysdata.md +50 -0
  96. package/dist/docs/1.deploy/2.providers/1.aws.md +47 -0
  97. package/dist/docs/1.deploy/2.providers/10.flightcontrol.md +67 -0
  98. package/dist/docs/1.deploy/2.providers/11.genezio.md +67 -0
  99. package/dist/docs/1.deploy/2.providers/12.github-pages.md +68 -0
  100. package/dist/docs/1.deploy/2.providers/13.gitlab-pages.md +37 -0
  101. package/dist/docs/1.deploy/2.providers/14.heroku.md +84 -0
  102. package/dist/docs/1.deploy/2.providers/15.iis.md +38 -0
  103. package/dist/docs/1.deploy/2.providers/16.koyeb.md +109 -0
  104. package/dist/docs/1.deploy/2.providers/17.netlify.md +47 -0
  105. package/dist/docs/1.deploy/2.providers/18.platform-sh.md +37 -0
  106. package/dist/docs/1.deploy/2.providers/19.render.md +37 -0
  107. package/dist/docs/1.deploy/2.providers/2.aws-amplify.md +81 -0
  108. package/dist/docs/1.deploy/2.providers/20.stormkit.md +24 -0
  109. package/dist/docs/1.deploy/2.providers/21.vercel.md +270 -0
  110. package/dist/docs/1.deploy/2.providers/22.zeabur.md +19 -0
  111. package/dist/docs/1.deploy/2.providers/23.zephyr.md +99 -0
  112. package/dist/docs/1.deploy/2.providers/24.zerops.md +102 -0
  113. package/dist/docs/1.deploy/2.providers/3.azure.md +72 -0
  114. package/dist/docs/1.deploy/2.providers/4.cleavr.md +33 -0
  115. package/dist/docs/1.deploy/2.providers/5.cloudflare.md +369 -0
  116. package/dist/docs/1.deploy/2.providers/6.deno-deploy.md +66 -0
  117. package/dist/docs/1.deploy/2.providers/7.digitalocean.md +46 -0
  118. package/dist/docs/1.deploy/2.providers/8.edgeone.md +20 -0
  119. package/dist/docs/1.deploy/2.providers/9.firebase.md +32 -0
  120. package/dist/docs/2.config/0.index/index.md +1221 -0
  121. package/dist/docs/3.examples/0.index/index.md +3 -0
  122. package/dist/docs/3.examples/1.api-routes.md +145 -0
  123. package/dist/docs/3.examples/10.hono.md +74 -0
  124. package/dist/docs/3.examples/11.import-alias.md +97 -0
  125. package/dist/docs/3.examples/12.middleware.md +91 -0
  126. package/dist/docs/3.examples/13.mono-jsx.md +68 -0
  127. package/dist/docs/3.examples/14.nano-jsx.md +70 -0
  128. package/dist/docs/3.examples/15.plugins.md +91 -0
  129. package/dist/docs/3.examples/16.renderer.md +113 -0
  130. package/dist/docs/3.examples/17.runtime-config.md +97 -0
  131. package/dist/docs/3.examples/18.server-fetch.md +87 -0
  132. package/dist/docs/3.examples/19.shiki.md +198 -0
  133. package/dist/docs/3.examples/2.auto-imports.md +92 -0
  134. package/dist/docs/3.examples/20.virtual-routes.md +74 -0
  135. package/dist/docs/3.examples/21.vite-nitro-plugin.md +79 -0
  136. package/dist/docs/3.examples/22.vite-rsc.md +1041 -0
  137. package/dist/docs/3.examples/23.vite-ssr-html.md +217 -0
  138. package/dist/docs/3.examples/24.vite-ssr-preact.md +247 -0
  139. package/dist/docs/3.examples/25.vite-ssr-react.md +226 -0
  140. package/dist/docs/3.examples/26.vite-ssr-solid.md +256 -0
  141. package/dist/docs/3.examples/27.vite-ssr-tsr-react.md +442 -0
  142. package/dist/docs/3.examples/28.vite-ssr-tss-react.md +444 -0
  143. package/dist/docs/3.examples/29.vite-ssr-vue-router.md +617 -0
  144. package/dist/docs/3.examples/3.cached-handler.md +81 -0
  145. package/dist/docs/3.examples/30.vite-trpc.md +335 -0
  146. package/dist/docs/3.examples/31.websocket.md +282 -0
  147. package/dist/docs/3.examples/4.custom-error-handler.md +98 -0
  148. package/dist/docs/3.examples/5.database.md +157 -0
  149. package/dist/docs/3.examples/6.elysia.md +70 -0
  150. package/dist/docs/3.examples/7.express.md +78 -0
  151. package/dist/docs/3.examples/8.fastify.md +79 -0
  152. package/dist/docs/3.examples/9.hello-world.md +68 -0
  153. package/dist/docs/README.md +86 -0
  154. package/dist/docs/index.md +121 -0
  155. package/dist/node_modules/@poppinss/dumper/build/formatters/html/main.js +8 -0
  156. package/dist/node_modules/@poppinss/dumper/package.json +1 -1
  157. package/dist/node_modules/@speed-highlight/core/dist/index.js +4 -4
  158. package/dist/node_modules/@speed-highlight/core/dist/terminal.js +2 -2
  159. package/dist/node_modules/@speed-highlight/core/package.json +1 -1
  160. package/dist/node_modules/cookie-es/dist/index.mjs +299 -250
  161. package/dist/node_modules/cookie-es/package.json +26 -23
  162. package/dist/node_modules/croner/dist/croner.js +1 -1
  163. package/dist/node_modules/croner/package.json +11 -1
  164. package/dist/node_modules/defu/dist/defu.mjs +2 -2
  165. package/dist/node_modules/defu/package.json +33 -28
  166. package/dist/node_modules/rendu/dist/_chunks/libs/cookie-es.mjs +151 -0
  167. package/dist/node_modules/rendu/dist/index.mjs +5 -112
  168. package/dist/node_modules/rendu/package.json +25 -24
  169. package/dist/node_modules/youch/build/helpers-B9BQYaS6.js +23 -0
  170. package/dist/node_modules/youch/build/index.js +204 -351
  171. package/dist/node_modules/youch/build/public/error_info/script.js +1 -1
  172. package/dist/node_modules/youch/build/public_dir-C5bujZKB.js +25 -0
  173. package/dist/node_modules/youch/build/src/templates/error_cause/main.js +44 -0
  174. package/dist/node_modules/youch/build/src/templates/error_info/main.js +72 -0
  175. package/dist/node_modules/youch/build/src/templates/error_metadata/main.js +65 -0
  176. package/dist/node_modules/youch/build/src/templates/error_stack/main.js +152 -0
  177. package/dist/node_modules/youch/build/src/templates/error_stack_source/main.js +46 -0
  178. package/dist/node_modules/youch/build/src/templates/header/main.js +24 -0
  179. package/dist/node_modules/youch/build/src/templates/layout/main.js +27 -0
  180. package/dist/node_modules/youch/package.json +35 -32
  181. package/dist/presets/_nitro/runtime/nitro-dev.mjs +12 -57
  182. package/dist/presets/_nitro/runtime/nitro-prerenderer.mjs +1 -0
  183. package/dist/presets/_nitro/runtime/service-worker.mjs +1 -2
  184. package/dist/presets/aws-lambda/runtime/_utils.mjs +6 -6
  185. package/dist/presets/aws-lambda/runtime/aws-lambda-streaming.mjs +3 -1
  186. package/dist/presets/azure/runtime/_utils.mjs +5 -5
  187. package/dist/presets/azure/runtime/azure-swa.mjs +5 -5
  188. package/dist/presets/bun/runtime/bun.mjs +9 -6
  189. package/dist/presets/cloudflare/runtime/_module-handler.mjs +1 -1
  190. package/dist/presets/cloudflare/runtime/cloudflare-durable.mjs +4 -4
  191. package/dist/presets/cloudflare/runtime/cloudflare-module.mjs +3 -3
  192. package/dist/presets/cloudflare/runtime/cloudflare-pages.mjs +2 -2
  193. package/dist/presets/cloudflare/runtime/plugin.dev.mjs +10 -21
  194. package/dist/presets/deno/runtime/deno-deploy.mjs +4 -4
  195. package/dist/presets/deno/runtime/deno-server.mjs +9 -6
  196. package/dist/presets/edgeone/runtime/edgeone.mjs +10 -0
  197. package/dist/presets/netlify/runtime/netlify-edge.mjs +2 -3
  198. package/dist/presets/netlify/runtime/netlify.mjs +1 -1
  199. package/dist/presets/node/runtime/node-cluster.mjs +5 -4
  200. package/dist/presets/node/runtime/node-middleware.mjs +1 -1
  201. package/dist/presets/node/runtime/node-server.mjs +8 -5
  202. package/dist/presets/stormkit/runtime/stormkit.mjs +1 -2
  203. package/dist/presets/vercel/runtime/cron-handler.mjs +25 -0
  204. package/dist/presets/vercel/runtime/queue-handler.mjs +21 -0
  205. package/dist/presets/vercel/runtime/vercel.node.mjs +3 -3
  206. package/dist/presets/vercel/runtime/vercel.web.mjs +3 -5
  207. package/dist/presets/winterjs/runtime/winterjs.mjs +10 -10
  208. package/dist/presets/zephyr/runtime/server.mjs +3 -0
  209. package/dist/runtime/internal/app.mjs +12 -11
  210. package/dist/runtime/internal/cache.d.mts +0 -4
  211. package/dist/runtime/internal/cache.mjs +32 -256
  212. package/dist/runtime/internal/context.d.mts +3 -1
  213. package/dist/runtime/internal/context.mjs +1 -9
  214. package/dist/runtime/internal/error/dev.d.mts +5 -4
  215. package/dist/runtime/internal/error/dev.mjs +47 -49
  216. package/dist/runtime/internal/error/hooks.d.mts +1 -1
  217. package/dist/runtime/internal/error/prod.d.mts +2 -5
  218. package/dist/runtime/internal/error/prod.mjs +19 -33
  219. package/dist/runtime/internal/error/utils.d.mts +4 -4
  220. package/dist/runtime/internal/meta.d.mts +1 -1
  221. package/dist/runtime/internal/plugin.d.mts +2 -2
  222. package/dist/runtime/internal/route-rules.d.mts +11 -4
  223. package/dist/runtime/internal/route-rules.mjs +15 -5
  224. package/dist/runtime/internal/routes/dev-tasks.d.mts +3 -2
  225. package/dist/runtime/internal/routes/dev-tasks.mjs +15 -10
  226. package/dist/runtime/internal/routes/openapi.mjs +2 -2
  227. package/dist/runtime/internal/routes/renderer-template.d.mts +1 -1
  228. package/dist/runtime/internal/routes/renderer-template.dev.d.mts +2 -1
  229. package/dist/runtime/internal/routes/scalar.mjs +3 -3
  230. package/dist/runtime/internal/routes/swagger.mjs +7 -4
  231. package/dist/runtime/internal/runtime-config.d.mts +1 -1
  232. package/dist/runtime/internal/runtime-config.mjs +2 -2
  233. package/dist/runtime/internal/static.mjs +5 -4
  234. package/dist/runtime/internal/task.d.mts +3 -1
  235. package/dist/runtime/internal/task.mjs +7 -7
  236. package/dist/runtime/internal/vite/dev-entry.mjs +6 -3
  237. package/dist/runtime/internal/vite/dev-worker.mjs +264 -0
  238. package/dist/runtime/meta.d.mts +1 -0
  239. package/dist/runtime/meta.mjs +2 -0
  240. package/dist/runtime/nitro.d.mts +2 -0
  241. package/dist/runtime/nitro.mjs +4 -2
  242. package/dist/runtime/virtual/error-handler.mjs +1 -1
  243. package/dist/runtime/virtual/renderer-template.mjs +1 -1
  244. package/dist/runtime/virtual/server-assets.d.mts +2 -1
  245. package/dist/runtime/virtual/tracing.d.mts +5 -0
  246. package/dist/runtime/virtual/tracing.mjs +1 -0
  247. package/dist/runtime/vite.d.mts +1 -1
  248. package/dist/types/index.d.mts +215 -195
  249. package/dist/types/index.mjs +1 -11
  250. package/dist/vite.d.mts +3 -8
  251. package/dist/vite.mjs +285 -253
  252. package/lib/tsconfig.json +3 -5
  253. package/package.json +97 -80
  254. package/dist/_libs/confbox.mjs +0 -2509
  255. package/dist/_libs/nypm+giget+tinyexec.mjs +0 -3603
  256. package/dist/_libs/rc9+c12+dotenv.mjs +0 -972
  257. package/dist/node_modules/hookable/dist/index.mjs +0 -266
  258. package/dist/node_modules/hookable/package.json +0 -52
  259. package/dist/node_modules/youch/build/chunk-4L7RY2JA.js +0 -42
  260. package/dist/node_modules/youch/build/chunk-7QV3D5YX.js +0 -83
  261. package/dist/node_modules/youch/build/chunk-AUGPHE32.js +0 -39
  262. package/dist/node_modules/youch/build/chunk-CM7DWJNZ.js +0 -44
  263. package/dist/node_modules/youch/build/chunk-EJH674NB.js +0 -223
  264. package/dist/node_modules/youch/build/chunk-OIJ3WD7L.js +0 -81
  265. package/dist/node_modules/youch/build/chunk-P36L72PL.js +0 -87
  266. package/dist/node_modules/youch/build/chunk-PE3GG3TN.js +0 -65
  267. package/dist/node_modules/youch/build/chunk-X53OIOJH.js +0 -70
  268. package/dist/presets/_nitro/runtime/nitro-dev.d.mts +0 -2
  269. package/dist/presets/_nitro/runtime/nitro-prerenderer.d.mts +0 -3
  270. package/dist/presets/_nitro/runtime/service-worker.d.mts +0 -2
  271. package/dist/presets/aws-amplify/runtime/aws-amplify.d.mts +0 -2
  272. package/dist/presets/aws-lambda/runtime/_utils.d.mts +0 -8
  273. package/dist/presets/aws-lambda/runtime/aws-lambda-streaming.d.mts +0 -2
  274. package/dist/presets/aws-lambda/runtime/aws-lambda.d.mts +0 -3
  275. package/dist/presets/azure/runtime/_utils.d.mts +0 -2
  276. package/dist/presets/azure/runtime/azure-swa.d.mts +0 -5
  277. package/dist/presets/bun/runtime/bun.d.mts +0 -3
  278. package/dist/presets/cloudflare/runtime/_module-handler.d.mts +0 -16
  279. package/dist/presets/cloudflare/runtime/cloudflare-durable.d.mts +0 -11
  280. package/dist/presets/cloudflare/runtime/cloudflare-module.d.mts +0 -3
  281. package/dist/presets/cloudflare/runtime/cloudflare-pages.d.mts +0 -20
  282. package/dist/presets/cloudflare/runtime/plugin.dev.d.mts +0 -3
  283. package/dist/presets/deno/runtime/deno-deploy.d.mts +0 -5
  284. package/dist/presets/deno/runtime/deno-server.d.mts +0 -3
  285. package/dist/presets/netlify/runtime/netlify-edge.d.mts +0 -3
  286. package/dist/presets/netlify/runtime/netlify.d.mts +0 -4
  287. package/dist/presets/node/runtime/node-cluster.d.mts +0 -3
  288. package/dist/presets/node/runtime/node-middleware.d.mts +0 -3
  289. package/dist/presets/node/runtime/node-server.d.mts +0 -3
  290. package/dist/presets/standard/runtime/server.d.mts +0 -3
  291. package/dist/presets/stormkit/runtime/stormkit.d.mts +0 -21
  292. package/dist/presets/vercel/runtime/isr.d.mts +0 -2
  293. package/dist/presets/vercel/runtime/vercel.node.d.mts +0 -3
  294. package/dist/presets/vercel/runtime/vercel.web.d.mts +0 -8
  295. package/dist/presets/winterjs/runtime/winterjs.d.mts +0 -2
  296. package/dist/presets/zeabur/runtime/zeabur.d.mts +0 -3
  297. package/dist/runtime/internal/vite/node-runner.mjs +0 -359
@@ -0,0 +1,239 @@
1
+ # Nitro Server Entry
2
+
3
+ > Use a server entry to create a global middleware that runs for all routes before they are matched.
4
+
5
+ The server entry is a special handler in Nitro that acts as a global middleware, running for every incoming request before routes are matched. It's commonly used for cross-cutting concerns like authentication, logging, request preprocessing, or creating custom routing logic.
6
+
7
+ ## Auto-detected `server.ts`
8
+
9
+ By default, Nitro automatically looks for a `server.ts` (or `.js`, `.mjs`, `.mts`, `.tsx`, `.jsx`) file in your project root directory.
10
+
11
+ If found, Nitro will use it as the server entry and run it for all incoming requests.
12
+
13
+ <code-group>
14
+
15
+ ```ts [server.ts]
16
+ export default {
17
+ async fetch(req: Request) {
18
+ const url = new URL(req.url);
19
+
20
+ // Handle specific routes
21
+ if (url.pathname === "/health") {
22
+ return new Response("OK", {
23
+ status: 200,
24
+ headers: { "content-type": "text/plain" }
25
+ });
26
+ }
27
+
28
+ // Add custom headers to all requests
29
+ // Return nothing to continue to the next handler
30
+ }
31
+ }
32
+ ```
33
+
34
+ ```ts [routes/api/hello.ts]
35
+ import { defineHandler } from "nitro";
36
+
37
+ export default defineHandler((event) => {
38
+ return { hello: "API" };
39
+ });
40
+ ```
41
+ </code-group>
42
+
43
+ <tip>
44
+
45
+ When `server.ts` is detected, Nitro will log in the terminal: `Detected \`server.ts` as server entry.`
46
+ </tip>
47
+
48
+ With this setup:
49
+
50
+ - `/health` → Handled by server entry (returns a response)
51
+ - `/api/hello` → Handled by the API route handler directly
52
+ - `/about`, etc. → Server entry runs first, then continues to the renderer if no response is returned
53
+
54
+ ## Framework compatibility
55
+ The server entry is a great way to integrate with other frameworks. Any framework that exposes a standard Web `fetch(request: Request): Response` interface can be used as a server entry.
56
+
57
+ ### Web-compatible frameworks
58
+
59
+ Frameworks that implement the Web `fetch` API work directly with `server.ts`:
60
+
61
+ <tabs>
62
+
63
+ <tabs-item>
64
+
65
+ ```ts [server.ts]
66
+ import { H3 } from "h3";
67
+
68
+ const app = new H3()
69
+
70
+ app.get("/", () => "⚡️ Hello from H3!");
71
+
72
+ export default app;
73
+ ```
74
+ </tabs-item>
75
+
76
+ <tabs-item>
77
+
78
+ ```ts [server.ts]
79
+ import { Hono } from "hono";
80
+
81
+ const app = new Hono();
82
+
83
+ app.get("/", (c) => c.text("🔥 Hello from Hono!"));
84
+
85
+ export default app;
86
+ ```
87
+ </tabs-item>
88
+
89
+ <tabs-item>
90
+
91
+ ```ts [server.ts]
92
+ import { Elysia } from "elysia";
93
+
94
+ const app = new Elysia();
95
+
96
+ app.get("/", () => "🦊 Hello from Elysia!");
97
+
98
+ export default app.compile();
99
+ ```
100
+ </tabs-item>
101
+ </tabs>
102
+
103
+ ### Node.js frameworks
104
+
105
+ For Node.js frameworks that use `(req, res)` style handlers (like [Express](https://expressjs.com/) or [Fastify](https://fastify.dev/)), name your server entry file `server.node.ts` instead of `server.ts`. Nitro will automatically detect the `.node.` suffix and convert the Node.js handler to a web-compatible fetch handler using [`srvx`](https://srvx.h3.dev/).
106
+
107
+ <tabs>
108
+
109
+ <tabs-item>
110
+
111
+ ```ts [server.node.ts]
112
+ import Express from "express";
113
+
114
+ const app = Express();
115
+
116
+ app.use("/", (_req, res) => {
117
+ res.send("Hello from Express with Nitro!");
118
+ });
119
+
120
+ export default app;
121
+ ```
122
+ </tabs-item>
123
+
124
+ <tabs-item>
125
+
126
+ ```ts [server.node.ts]
127
+ import Fastify from "fastify";
128
+
129
+ const app = Fastify();
130
+
131
+ app.get("/", () => "Hello, Fastify with Nitro!");
132
+
133
+ await app.ready();
134
+
135
+ export default app.routing;
136
+ ```
137
+ </tabs-item>
138
+ </tabs>
139
+
140
+ ## Configuration
141
+
142
+ ### Custom server entry file
143
+
144
+ You can specify a custom server entry file using the `serverEntry` option in your Nitro configuration:
145
+
146
+ ```ts [nitro.config.ts]
147
+ import { defineConfig } from "nitro";
148
+
149
+ export default defineConfig({
150
+ serverEntry: "./nitro.server.ts"
151
+ })
152
+ ```
153
+
154
+ You can also provide an object with `handler` and `format` options:
155
+
156
+ ```ts [nitro.config.ts]
157
+ import { defineConfig } from "nitro";
158
+
159
+ export default defineConfig({
160
+ serverEntry: {
161
+ handler: "./server.ts",
162
+ format: "node" // "web" (default) or "node"
163
+ }
164
+ })
165
+ ```
166
+
167
+ ### Handler format
168
+
169
+ The `format` option controls how Nitro treats the default export of your server entry:
170
+
171
+ - **`"web"`** (default) — Expects a Web-compatible handler with a `fetch(request: Request): Response` method.
172
+ - **`"node"`** — Expects a Node.js-style `(req, res)` handler. Nitro automatically converts it to a web-compatible handler.
173
+ When auto-detecting, the format is determined by the filename: `server.node.ts` uses `"node"` format, while `server.ts` uses `"web"` format.
174
+
175
+ ### Disabling server entry
176
+
177
+ Set `serverEntry` to `false` to disable auto-detection and prevent Nitro from using any server entry:
178
+
179
+ ```ts [nitro.config.ts]
180
+ import { defineConfig } from "nitro";
181
+
182
+ export default defineConfig({
183
+ serverEntry: false
184
+ })
185
+ ```
186
+
187
+ ## Using event handler
188
+
189
+ You can also export an event handler using `defineHandler` for better type inference and access to the h3 event object:
190
+
191
+ ```ts [server.ts]
192
+ import { defineHandler } from "nitro";
193
+
194
+ export default defineHandler((event) => {
195
+ // Add custom context
196
+ event.context.requestId = crypto.randomUUID();
197
+ event.context.timestamp = Date.now();
198
+
199
+ // Log the request
200
+ console.log(`[${event.context.requestId}] ${event.method} ${event.path}`);
201
+
202
+ // Continue to the next handler (don't return anything)
203
+ });
204
+ ```
205
+
206
+ <important>
207
+
208
+ If your server entry returns `undefined` or doesn't return anything, the request will continue to be processed by routes and the renderer. If it returns a response, the request lifecycle stops there.
209
+ </important>
210
+
211
+ ## Request lifecycle
212
+
213
+ The server entry is registered as a catch-all (`/**`) route handler. When a specific route (like `/api/hello`) matches a request, that route handler takes priority. For requests that don't match any specific route, the server entry runs before the renderer:
214
+
215
+ ```md
216
+ 1. Server hook: `request`
217
+ 2. Route rules (headers, redirects, etc.)
218
+ 3. Global middleware (middleware/)
219
+ 4. Route matching:
220
+ a. Specific routes (routes/) ← if matched, handles the request
221
+ b. Server entry ← runs for unmatched routes
222
+ c. Renderer (renderer.ts or index.html)
223
+ ```
224
+
225
+ When both a server entry and a renderer exist, they are chained: the server entry runs first, and if it doesn't return a response, the renderer handles the request.
226
+
227
+ ## Development mode
228
+
229
+ During development, Nitro watches for changes to your server entry file. When the file is created, modified, or deleted, the dev server automatically reloads to pick up the changes.
230
+
231
+ ## Best practices
232
+
233
+ - Use server entry for cross-cutting concerns that affect **all routes**
234
+ - Return `undefined` to continue processing, return a response to terminate
235
+ - Keep server entry logic lightweight for better performance
236
+ - Use global middleware for modular concerns instead of one large server entry
237
+ - Consider using [Nitro plugins](/docs/plugins) for initialization logic
238
+ - Avoid heavy computation in server entry (it runs for every request)
239
+ - Don't use server entry for route-specific logic (use route handlers instead as they are more performant)
@@ -0,0 +1,408 @@
1
+ # Cache
2
+
3
+ > Nitro provides a caching system built on top of the storage layer, powered by [ocache](https://github.com/unjs/ocache).
4
+
5
+ ## Cached handlers
6
+
7
+ To cache an event handler, you simply need to use the `defineCachedHandler` method.
8
+
9
+ It works like `defineHandler` but with an second parameter for the [cache options](#options).
10
+
11
+ ```ts [routes/cached.ts]
12
+ import { defineCachedHandler } from "nitro/cache";
13
+
14
+ export default defineCachedHandler((event) => {
15
+ return "I am cached for an hour";
16
+ }, { maxAge: 60 * 60 });
17
+ ```
18
+
19
+ With this example, the response will be cached for 1 hour and a stale value will be sent to the client while the cache is being updated in the background. If you want to immediately return the updated response set `swr: false`.
20
+
21
+ See the [options](#options) section for more details about the available options.
22
+
23
+ <important>
24
+
25
+ **Request headers are dropped** when handling cached responses. Use the [`varies` option](#options) to consider specific headers when caching and serving the responses.
26
+ </important>
27
+
28
+ ### Automatic HTTP headers
29
+
30
+ When using `defineCachedHandler`, Nitro automatically manages HTTP cache headers on cached responses:
31
+
32
+ - **`etag`** -- A weak ETag (`W/"..."`) is generated from the response body hash if not already set by the handler.
33
+ - **`last-modified`** -- Set to the current time when the response is first cached, if not already set.
34
+ - **`cache-control`** -- Automatically set based on the `swr`, `maxAge`, and `staleMaxAge` options: - With `swr: true`: `s-maxage=<maxAge>, stale-while-revalidate=<staleMaxAge>`
35
+ - With `swr: false`: `max-age=<maxAge>`
36
+
37
+
38
+ ### Conditional requests (304 Not Modified)
39
+ Cached handlers automatically support conditional requests. When a client sends `if-none-match` or `if-modified-since` headers matching the cached response, Nitro returns a `304 Not Modified` response without a body.
40
+
41
+ ### Request method filtering
42
+
43
+ Only `GET` and `HEAD` requests are cached. All other HTTP methods (`POST`, `PUT`, `DELETE`, etc.) automatically bypass the cache and call the handler directly.
44
+
45
+ ### Request deduplication
46
+
47
+ When multiple concurrent requests hit the same cache key while the cache is being resolved, only one invocation of the handler runs. All concurrent requests wait for and share the same result.
48
+
49
+ ## Cached functions
50
+
51
+ You can also cache a function using the `defineCachedFunction` function. This is useful for caching the result of a function that is not an event handler, but is part of one, and reusing it in multiple handlers.
52
+
53
+ For example, you might want to cache the result of an API call for one hour:
54
+
55
+ ```ts [routes/api/stars/[...repo\].ts]
56
+ import { defineCachedFunction } from "nitro/cache";
57
+ import { defineHandler, type H3Event } from "nitro";
58
+
59
+ export default defineHandler(async (event) => {
60
+ const { repo } = event.context.params;
61
+ const stars = await cachedGHStars(repo).catch(() => 0)
62
+
63
+ return { repo, stars }
64
+ });
65
+
66
+ const cachedGHStars = defineCachedFunction(async (repo: string) => {
67
+ const data = await fetch(`https://api.github.com/repos/${repo}`).then(res => res.json());
68
+
69
+ return data.stargazers_count;
70
+ }, {
71
+ maxAge: 60 * 60,
72
+ name: "ghStars",
73
+ getKey: (repo: string) => repo
74
+ });
75
+ ```
76
+
77
+ The stars will be cached in development inside `.nitro/cache/functions/ghStars/<owner>/<repo>.json` with `value` being the number of stars.
78
+
79
+ ```json
80
+ {"expires":1677851092249,"value":43991,"mtime":1677847492540,"integrity":"ZUHcsxCWEH"}
81
+ ```
82
+
83
+ <important>
84
+
85
+ Because the cached data is serialized to JSON, it is important that the cached function does not return anything that cannot be serialized, such as Symbols, Maps, Sets...
86
+ </important>
87
+
88
+ <callout>
89
+
90
+ If you are using edge workers to host your application, you should follow the instructions below.
91
+ :<collapsible></collapsible>
92
+ In edge workers, the instance is destroyed after each request. Nitro automatically uses `event.waitUntil` to keep the instance alive while the cache is being updated while the response is sent to the client.
93
+
94
+ To ensure that your cached functions work as expected in edge workers, **you should always pass the `event` as the first argument to the function using `defineCachedFunction`.**
95
+
96
+ ```ts [routes/api/stars/[...repo\].ts] {5,10,17}
97
+ import { defineCachedFunction } from "nitro/cache";
98
+
99
+
100
+ export default defineHandler(async (event) => {
101
+ const { repo } = event.context.params;
102
+ const stars = await cachedGHStars(event, repo).catch(() => 0)
103
+
104
+ return { repo, stars }
105
+ });
106
+
107
+ const cachedGHStars = defineCachedFunction(async (event: H3Event, repo: string) => {
108
+ const data = await fetch(`https://api.github.com/repos/${repo}`).then(res => res.json());
109
+
110
+ return data.stargazers_count;
111
+ }, {
112
+ maxAge: 60 * 60,
113
+ name: "ghStars",
114
+ getKey: (event: H3Event, repo: string) => repo
115
+ });
116
+ ```
117
+
118
+ This way, the function will be able to keep the instance alive while the cache is being updated without slowing down the response to the client.
119
+ </callout>
120
+
121
+ ::
122
+
123
+ ## Using route rules
124
+
125
+ This feature enables you to add caching routes based on a glob pattern directly in the main configuration file. This is especially useful to have a global cache strategy for a part of your application.
126
+
127
+ Cache all the blog routes for 1 hour with `stale-while-revalidate` behavior:
128
+
129
+ ```ts [nitro.config.ts]
130
+ import { defineConfig } from "nitro";
131
+
132
+ export default defineConfig({
133
+ routeRules: {
134
+ "/blog/**": { cache: { maxAge: 60 * 60 } },
135
+ },
136
+ });
137
+ ```
138
+
139
+ If we want to use a [custom cache storage](#cache-storage) mount point, we can use the `base` option.
140
+
141
+ ```ts [nitro.config.ts]
142
+ import { defineConfig } from "nitro";
143
+
144
+ export default defineConfig({
145
+ storage: {
146
+ redis: {
147
+ driver: "redis",
148
+ url: "redis://localhost:6379",
149
+ },
150
+ },
151
+ routeRules: {
152
+ "/blog/**": { cache: { maxAge: 60 * 60, base: "redis" } },
153
+ },
154
+ });
155
+ ```
156
+
157
+ ### Route rules shortcuts
158
+
159
+ You can use the `swr` shortcut for enabling `stale-while-revalidate` caching on route rules. When set to `true`, SWR is enabled with the default `maxAge`. When set to a number, it is used as the `maxAge` value in seconds.
160
+
161
+ ```ts [nitro.config.ts]
162
+ import { defineConfig } from "nitro";
163
+
164
+ export default defineConfig({
165
+ routeRules: {
166
+ "/blog/**": { swr: true },
167
+ "/api/**": { swr: 3600 },
168
+ },
169
+ });
170
+ ```
171
+
172
+ To explicitly disable caching on a route, set `cache: false`:
173
+
174
+ ```ts [nitro.config.ts]
175
+ import { defineConfig } from "nitro";
176
+
177
+ export default defineConfig({
178
+ routeRules: {
179
+ "/api/realtime/**": { cache: false },
180
+ },
181
+ });
182
+ ```
183
+
184
+ <note>
185
+
186
+ When using route rules, cached handlers use the group `'nitro/route-rules'` instead of the default `'nitro/handlers'`.
187
+ </note>
188
+
189
+ ## Cache storage
190
+
191
+ Nitro stores the data in the `cache` storage mount point.
192
+
193
+ - In production, it will use the [memory driver](https://unstorage.unjs.io/drivers/memory) by default.
194
+ - In development, it will use the [filesystem driver](https://unstorage.unjs.io/drivers/fs), writing to a temporary dir (`.nitro/cache`).
195
+ To overwrite the production storage, set the `cache` mount point using the `storage` option:
196
+
197
+ ```ts [nitro.config.ts]
198
+ import { defineConfig } from "nitro";
199
+
200
+ export default defineConfig({
201
+ storage: {
202
+ cache: {
203
+ driver: 'redis',
204
+ /* redis connector options */
205
+ }
206
+ }
207
+ })
208
+ ```
209
+
210
+ In development, you can also overwrite the cache mount point using the `devStorage` option:
211
+
212
+ ```ts [nitro.config.ts]
213
+ import { defineConfig } from "nitro";
214
+
215
+ export default defineConfig({
216
+ storage: {
217
+ cache: {
218
+ // production cache storage
219
+ },
220
+ },
221
+ devStorage: {
222
+ cache: {
223
+ // development cache storage
224
+ }
225
+ }
226
+ })
227
+ ```
228
+
229
+ ## Options
230
+
231
+ The `defineCachedHandler` and `defineCachedFunction` functions accept the following options:
232
+
233
+ ### Shared options
234
+
235
+ These options are available for both `defineCachedHandler` and `defineCachedFunction`:
236
+
237
+ <field-group>
238
+
239
+ <field>
240
+
241
+ Name of the storage mountpoint to use for caching. :br
242
+ Default to `cache`.
243
+ </field>
244
+
245
+ <field>
246
+
247
+ Guessed from function name if not provided, and falls back to `'_'` otherwise.
248
+ </field>
249
+
250
+ <field>
251
+
252
+ Defaults to `'nitro/handlers'` for handlers and `'nitro/functions'` for functions.
253
+ </field>
254
+
255
+ <field>
256
+
257
+ A function that accepts the same arguments as the original function and returns a cache key (`String`). :br
258
+ If not provided, a built-in hash function will be used to generate a key based on the function arguments. For cached handlers, the key is derived from the request URL path and search params.
259
+ </field>
260
+
261
+ <field>
262
+
263
+ A value that invalidates the cache when changed. :br
264
+ By default, it is computed from **function code**, used in development to invalidate the cache when the function code changes.
265
+ </field>
266
+
267
+ <field>
268
+
269
+ Maximum age that cache is valid, in seconds. :br
270
+ Default to `1` (second).
271
+ </field>
272
+
273
+ <field>
274
+
275
+ Maximum age that a stale cache is valid, in seconds. If set to `-1` a stale value will still be sent to the client while the cache updates in the background. :br
276
+ Defaults to `0` (disabled).
277
+ </field>
278
+
279
+ <field>
280
+
281
+ Enable `stale-while-revalidate` behavior to serve a stale cached response while asynchronously revalidating it. :br
282
+ When enabled, stale cached values are returned immediately while revalidation happens in the background. When disabled, the caller waits for the fresh value before responding (the stale entry is cleared). :br
283
+ Defaults to `true`.
284
+ </field>
285
+
286
+ <field>
287
+
288
+ A function that returns a `boolean` to invalidate the current cache and create a new one.
289
+ </field>
290
+
291
+ <field>
292
+
293
+ A function that returns a `boolean` to bypass the current cache without invalidating the existing entry.
294
+ </field>
295
+
296
+ <field>
297
+
298
+ A custom error handler called when the cached function throws. :br
299
+ By default, errors are logged to the console and captured by the Nitro error handler.
300
+ </field>
301
+ </field-group>
302
+
303
+ ### Handler-only options
304
+
305
+ These options are only available for `defineCachedHandler`:
306
+
307
+ <field-group>
308
+
309
+ <field>
310
+
311
+ When `true`, skip full response caching and only handle conditional request headers (`if-none-match`, `if-modified-since`) for `304 Not Modified` responses. The handler is called on every request but benefits from conditional caching.
312
+ </field>
313
+
314
+ <field>
315
+
316
+ An array of request header names to vary the cache key on. Headers listed here are preserved on the request during cache resolution and included in the cache key, making the cache unique per combination of header values. :br :br
317
+ Headers **not** listed in `varies` are stripped from the request before calling the handler to ensure consistent cache hits. :br :br
318
+ For multi-tenant environments, you may want to pass `['host', 'x-forwarded-host']` to ensure these headers are not discarded and that the cache is unique per tenant.
319
+ </field>
320
+ </field-group>
321
+
322
+ ### Function-only options
323
+
324
+ These options are only available for `defineCachedFunction`:
325
+
326
+ <field-group>
327
+
328
+ <field>
329
+
330
+ Transform the cache entry before returning. The return value replaces the cached value.
331
+ </field>
332
+
333
+ <field>
334
+
335
+ Validate a cache entry. Return `false` to treat the entry as invalid and trigger re-resolution.
336
+ </field>
337
+ </field-group>
338
+
339
+ ## SWR behavior
340
+
341
+ The `stale-while-revalidate` (SWR) pattern is enabled by default (`swr: true`). Understanding how it interacts with other options:
342
+
343
+ | `swr` | `maxAge` | Behavior |
344
+ | --- | --- | --- |
345
+ | `true` (default) | `1` (default) | Cache for 1 second, serve stale while revalidating |
346
+ | `true` | `3600` | Cache for 1 hour, serve stale while revalidating |
347
+ | `false` | `3600` | Cache for 1 hour, wait for fresh value when expired |
348
+ | `true` | `3600` with `staleMaxAge: 600` | Cache for 1 hour, serve stale for up to 10 minutes while revalidating |
349
+
350
+ When `swr` is enabled and a cached value exists but has expired:
351
+
352
+ 1. The stale cached value is returned immediately to the client.
353
+ 2. The function/handler is called in the background to refresh the cache.
354
+ 3. On edge workers, `event.waitUntil` is used to keep the background refresh alive.
355
+ When `swr` is disabled and a cached value has expired:
356
+
357
+ 1. The stale entry is cleared.
358
+ 2. The client waits for the function/handler to resolve with a fresh value.
359
+
360
+ ## Cache keys and invalidation
361
+ When using the `defineCachedFunction` or `defineCachedHandler` functions, the cache key is generated using the following pattern:
362
+
363
+ ```ts
364
+ `${options.base}:${options.group}:${options.name}:${options.getKey(...args)}.json`
365
+ ```
366
+
367
+ For example, the following function:
368
+
369
+ ```ts
370
+ import { defineCachedFunction } from "nitro/cache";
371
+
372
+ const getAccessToken = defineCachedFunction(() => {
373
+ return String(Date.now())
374
+ }, {
375
+ maxAge: 10,
376
+ name: "getAccessToken",
377
+ getKey: () => "default"
378
+ });
379
+ ```
380
+
381
+ Will generate the following cache key:
382
+
383
+ ```ts
384
+ cache:nitro/functions:getAccessToken:default.json
385
+ ```
386
+
387
+ You can invalidate the cached function entry with:
388
+
389
+ ```ts
390
+ import { useStorage } from "nitro/storage";
391
+
392
+ await useStorage('cache').removeItem('nitro/functions:getAccessToken:default.json')
393
+ ```
394
+
395
+ <note>
396
+
397
+ For cached handlers, the cache key includes a hash of the URL path and, when using the [`varies`](#handler-only-options) option, hashes of the specified header values appended to the key.
398
+ </note>
399
+
400
+ <note>
401
+
402
+ Responses with HTTP status codes `>= 400` or with an undefined body are not cached. This prevents caching error responses.
403
+ </note>
404
+
405
+ <read-more>
406
+
407
+ Read more about the Nitro storage.
408
+ </read-more>