nitro icon indicating copy to clipboard operation
nitro copied to clipboard

[vite] `$fetch` is undefined during `vite dev`

Open alan-agius4 opened this issue 4 months ago • 2 comments

Environment

Node: 22.18.0 nitro-nightly: 3.0.0-20250717-115429.740761af

Reproduction

In https://github.com/nitrojs/vite-examples/blob/a35209b42b1b6dc0ef99cdf36a5e8eab11d90bea/examples/basic-service/server.ts#L3 add the below

  console.log({
      'globalThis.$fetch': globalThis.$fetch
 })

Describe the bug

Global $fetch is undefined during vite dev but defined when using vite build

Additional context

No response

Logs

$ vite dev

  VITE v7.0.5  ready in 796 ms

  ➜  Local:   http://localhost:5174/
  ➜  Network: use --host to expose
  ➜  press h + enter to show help
{ 'globalThis.$fetch': undefined }


$ vite build
◐ Building SSR...                                                                                                                                                                                                       nitro 11:04:00 AM
vite v7.0.5 building SSR bundle for production...
✓ 1 modules transformed.
.nitro/vite/services/ssr/server.mjs  0.21 kB
✓ built in 42ms
◐ Building Nitro Server (preset: node-server, compatibility date: 2025-08-27)                                                                                                                                           nitro 11:04:00 AM
✔ Generated public .output/public                                                                                                                                                                                      nitro 11:04:00 AM
vite v7.0.5 building SSR bundle for production...
✓ 77 modules transformed.
.output/server/chunks/build/server.mjs    0.21 kB
.output/server/index.mjs                151.13 kB
✓ built in 683ms
✔ You can preview this build using node .output/server/index.mjs                                                                                                                                                       nitro 11:04:01 AM


$ node .output/server/index.mjs
Listening on http://[::]:3000
{
  'globalThis.$fetch': [AsyncFunction: $fetch2] {
    raw: [AsyncFunction: $fetchRaw2],
    native: [Function (anonymous)],
    create: [Function (anonymous)]
  }
}

alan-agius4 avatar Aug 27 '25 11:08 alan-agius4

Thanks for the report. It is a known issue with the current v3.

I suggest migrating to useNitroApp().fetch and normal fetch

pi0 avatar Aug 27 '25 11:08 pi0

I just tried using useNitroApp().fetch.

import { useNitroApp } from 'nitro/runtime'

export default {
  fetch: (req: Request): Response | Promise<Response> => {
    console.log(useNitroApp().fetch)
    return new Response("Hello from Nitro Vite Basic Service!");
  },
};

This however now causes the following issue: https://github.com/nitrojs/nitro/issues/3551

alan-agius4 avatar Aug 27 '25 11:08 alan-agius4