"TypeError: fetch failed" in production but not preview
Describe the bug
I'm getting this error
[500] GET /blog
TypeError: fetch failed
at node:internal/deps/undici/undici:14900:13
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async fetch (file:///home/siddharth/projects/personal-site/build/server/index.js:7374:18)
When fetching, but only in a production build. In the preview version it works perfectly.
Here's what my directory tree looks like
[nix-shell:~/projects/personal-site]$ tree -I 'node_modules|build' -L 4
.
├── package.json
├── package-lock.json
├── src
│ ├── app.d.ts
│ ├── app.html
│ ├── lib
│ │ └── index.ts
│ └── routes
│ ├── +layout.svelte
│ ├── +page.svelte
│ └── [...slug]
│ ├── +page.svelte
│ └── +page.ts
├── static
│ ├── build
│ │ ├── blog
│ │ │ └── blog-post.html
│ │ ├── blog.html
│ │ └── index.html
│ └── favicon.png
├── svelte.config.js
├── tsconfig.json
└── vite.config.ts
And importantly, src/routes/[...slug]/+page.ts contains
import { error } from "@sveltejs/kit"
// Uses the correct fetch
export async function load({ fetch, params, url }) {
let slug = params.slug
if (!slug) {
slug = "index"
}
// Catch any /build paths not in /static
if (url.pathname.startsWith("/build")) {
return error(404)
}
let response = await fetch('/build/' + params.slug + '.html')
if (!response.ok) {
return
}
let html = await response.text()
return { html: html }
}
My understanding is that the client will always request the page from the server, because I have data-sveltekit-reload set in app.html
Then the server, running load attempts to fetch /build/blog.html and for some reason fails.
Reproduction
The repro can be found at https://github.com/siddharth-narayan/personal-site/tree/repro -- A stripped down version of my project that I feel contains the bare minimum to reproduce. All that's needed should be an npm install and then either npm run build && node build or npm run preview
Logs
System Info
System:
OS: Linux 6.12 cpe:/o:nixos:nixos:25.11 25.11 (Xantusia)
CPU: (8) x64 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
Memory: 23.86 GB / 31.14 GB
Container: Yes
Shell: 5.3.3 - /nix/store/35yc81pz0q5yba14lxhn5r3jx5yg6c3l-bash-interactive-5.3p3/bin/bash
Binaries:
Node: 22.21.1 - /nix/store/l85fis49agvp5q1ild1rfh4rrgmn92sr-nodejs-22.21.1/bin/node
npm: 10.9.4 - /nix/store/l85fis49agvp5q1ild1rfh4rrgmn92sr-nodejs-22.21.1/bin/npm
Browsers:
Chromium: 142.0.7444.175
Firefox: 145.0.2
Firefox Developer Edition: 145.0.2
npmPackages:
@sveltejs/adapter-auto: ^3.0.0 => 3.3.1
@sveltejs/adapter-node: ^5.0.0 => 5.4.0
@sveltejs/kit: ^2.0.0 => 2.48.4
@sveltejs/vite-plugin-svelte: ^6.0.0 => 6.2.1
svelte: ^5.0.0 => 5.43.6
vite: ^7.0.0 => 7.2.2
Severity
serious, but I can work around it -- I can't serve a fully built version of my personal site, I have to serve the preview version
Additional Information
No response
The reason this is happening is because there's no way (as you've written everything) for SvelteKit / Vite to know you're actually using those assets in static/build, so when you run your build script, they're not getting bundled with your application (and therefore don't "exist" at runtime).
Is there a reason you're trying to use static HTML files like this?
Here's what's happening:
- Navigating to
/bloginvokes the Node adapter's SSR handler because it doesn't match a prerendered page or static asset - The SvelteKit server matches the
[...slug]/+page.tsroute and runs the load function there - The load function uses SvelteKit's load function
fetchwhich avoids making a network request by trying to read the static asset from the Vite manifest (assets located in the static folder before building) or finding a matching route - It matches
/build/blog.htmlto[...slug]/+page.tswhich runs the load function again but returns a 404 because it starts with/build.
For static assets included after build. They can be accessed by directly hitting the Node server which will server the static file at that path instead of invoking the SSR handler (you should use the non-SvelteKit load function fetch to do this). Or by reading directly from the filesystem with fs.
I think this is working as intended because your rest param route is matching /build/blog.html, so SvelteKit would never be able to know that it needs to fallback to a native fetch to retrieve whatever may or may not be at that path.
4. It matches
/build/blog.htmlto[...slug]/+page.tswhich runs the load function again but returns a 404 because it starts with/build.
I think this part is incorrect? My understanding is that it matches static assets with higher priority than matching a route
I think the more likely explanation is that it's not bundled, in which case I wonder why the response is not a simple 404 but a server side error? Also how can I make the bundler include ALL static assets?
The reason I'm using html like this is because I just want a simple system for blog posts, built with typst. I feel like this should work -- it's probably the most basic way of serving a mostly static webpage with sveltekit I can think of
- It matches
/build/blog.htmlto[...slug]/+page.tswhich runs the load function again but returns a 404 because it starts with/build.I think this part is incorrect? My understanding is that it matches static assets with higher priority than matching a route
The order of precedence for client to server is
- filesystem
- SSR (matches a page route)
The order of precedence for server to server (which is what the server load function provided fetch does) is:
- known static assets in the Vite manifest (exists before build)
- SSR (matches a page route)
- fallback to native fetch
I think the more likely explanation is that it's not bundled, in which case I wonder why the response is not a simple 404 but a server side error? Also how can I make the bundler include ALL static assets?
To include a static asset in Vite's pipeline, it needs to either be in the /static directory, imported in a js module, or referenced in a CSS file's URL() constructor
Right, so given that precedence:
- filesystem -- Not matched
- SSR (matches a page route) -- Matched
- known static assets -- Matched?
- SSR
- native fetch (what is this one?)
Shouldn't this strategy of serving content work? All the static html files should be included in the build from what you're describing.
1. known static assets -- Matched?
Only if the files were in the /static folder before the build. Vite needs a way to know about these files to include it in its static asset manifest and it can't do that when it's added after the build. Based on Elliot's reply https://github.com/sveltejs/kit/issues/15011#issuecomment-3608710556 I think those static files generated by typyst are being done after the build? Correct me if I'm wrong.
3. native fetch (what is this one?)
This is equivalent to fetch('https://example.com'). It's just an ordinary fetch without SvelteKit trying to skip the network call. It's similar to the client -> server fetch.
No those static files are there before build. There's two build steps -- one to compile typst -> html, and the other to build the site itself. You can see the makefile that I run separately to generate html in /static on the main branch, not the repro branch
Are you able to reproduce the problem?
Are you able to reproduce the problem?
Hi Siddharth. I'm so sorry I haven't been able to get back to you swiftly. I've been swamped trying to complete a client project as the year ends. I will have more time for SvelteKit next month as this is my last month at my current company. Please let me know if this is urgent and I'll try to squeeze it in closer to the Christmas holidays when I'm on leave.
No worries, please don't feel any pressure at all to respond quickly, its not urgent whatseover. It's just for my personal website, so I can wait indefinitely, it doesn't matter to me at all :)
I can't seem to reproduce this locally. It's possible that you'll need to set the paths.origin setting so that your relative fetch fetches from the correct origin https://svelte.dev/docs/kit/@sveltejs-kit-vite#paths
Thank you so much for following up! I'd really like to fix this issue, I'm still running my website on preview!
I'm still able to reproduce this on all 3 of my machines, Windows, Linux, + Linux Server (And a VM just to make sure). I fully updated dependencies as well, and also took your suggestion of setting paths.origin, which I set to "http://localhost"
After the update I get a slightly different error message, but clearly the same error:
TypeError: fetch failed
AggregateError [ECONNREFUSED]:
at internalConnectMultiple (node:net:1426:18)
at afterConnectMultiple (node:net:2095:7)
Are you using my repro branch?
Also, I just want to stress that even if I've somehow messed something up, I'm not getting a 404 but a 500 error, which I seems like it shouldn't be happening.
If you still can't reproduce it, is there any other information you want me to provide, or anything else I can do to debug it for you?
and also took your suggestion of setting
paths.origin, which I set to"http://localhost"
Does that include the port your server is hosted from?
Are you using my repro branch? Also, I just want to stress that even if I've somehow messed something up, I'm not getting a 404 but a 500 error, which I seems like it shouldn't be happening.
Yes, I've used the linked repository. It's a 500 error presumably because it's trying to fetch from a host that it can't connect to. You can reproduce the same error by running fetch('http://localhost') inside Node.js while that host doesn't exist
Yes adding the port works!!
Do you have any idea why it fails without setting paths.origin? Especially during development, I have no reverse proxy blocking the hosts header, and I also have to manually change it depending on where it's deployed. Is there any reason that the origin is unable to be guessed correctly?
Thank you for your help!
See https://svelte.dev/docs/kit/adapter-node#Environment-variables-PROTOCOL_HEADER-HOST_HEADER-and-PORT_HEADER
Previously, you'd set the ORIGIN environment variable and we might bring that back https://github.com/sveltejs/kit/issues/17328