`Error: connect ECONNREFUSED` When Using `postgres` After Upgrading to Version `@sveltejs/[email protected]` (or Higher)
Describe the bug
I noticed that some apps I work on, which use both SvelteKit and the postgres package, are returning 500 errors.
I dug deeper, and it seems the errors are coming from code like this (this is a fake example that is similar to the real thing):
// hooks.server.ts
const authHandle: Handle = async ({ event, resolve }) => {
const uuid = getUserUuid(event);
if (uuid === null || typeof uuid !== "string") {
event.locals.userUuid = null;
event.locals.isAuthenticated = false;
event.locals.userPermissions = new Set();
return resolve(event);
}
event.locals.userUuid = uuid;
event.locals.isAuthenticated = true;
const [row]: [{ permission_names: Array<string> }] = await raw.sql`
-- Query to get the user permissions.
`;
event.locals.userPermissions = new Set(row?.permission_names || []);
return resolve(event);
};
export const handle = sequence(Sentry.sentryHandle(), authHandle);
export const handleError = Sentry.handleErrorWithSentry();
The part where I query the DB throws this error:
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1637:16)
at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17)
at cachedError (file:///home/node/app/node_modules/postgres/src/query.js:170:23)
at new Query (file:///home/node/app/node_modules/postgres/src/query.js:36:24)
at Object.sql (file:///home/node/app/node_modules/postgres/src/index.js:112:11)
at authHandle (file:///home/node/app/build/server/chunks/hooks.server-B4mVD8io.js:201:30)
Downgrading to @sveltejs/[email protected] "fixes" the issue.
Also, the error is not thrown in development, only when the app is built and deployed.
Reproduction
- Create a new SvelteKit project.
- Add
postgrespackage. - Create a
hooks.server.tsfile. - Create a custom handle function.
- Write any query inside the function.
- Build the app.
- Navigate to the application URL.
- An error 500 is returned.
Logs
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1637:16)
at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17)
at cachedError (file:///home/node/app/node_modules/postgres/src/query.js:170:23)
at new Query (file:///home/node/app/node_modules/postgres/src/query.js:36:24)
at Object.sql (file:///home/node/app/node_modules/postgres/src/index.js:112:11)
at authHandle (file:///home/node/app/build/server/chunks/hooks.server-B4mVD8io.js:201:30)
System Info
System:
OS: Windows 11 10.0.26100
CPU: (28) x64 Intel(R) Core(TM) i7-14700K
Memory: 34.47 GB / 63.70 GB
Binaries:
Node: 22.19.0 - C:\Program Files\nodejs\node.EXE
npm: 11.6.0 - ~\AppData\Roaming\npm\npm.CMD
bun: 1.2.21 - ~\.bun\bin\bun.EXE
Browsers:
Edge: Chromium (140.0.3485.54)
Internet Explorer: 11.0.26100.1882
npmPackages:
@sveltejs/adapter-node: 5.3.2 => 5.3.2
@sveltejs/kit: 2.39.1 => 2.39.1
@sveltejs/vite-plugin-svelte: ^6.2.0 => 6.2.0
svelte: ^5.38.10 => 5.38.10
vite: ^7.1.5 => 7.1.5
Severity
blocking all usage of SvelteKit
Additional Information
- The issue can ONLY be observed when the application is built. It does NOT occur during development.
- I double checked my environment configuration files, and everything is as it should be.
- I tried downgrading/upgrading different packages, but only when I downgraded SvelteKit was the issue resolved.
Probably related happens to me as well, all my remote functions that make a database call using drizzle stops working after upgrading to @sveltejs/[email protected] or above. May be something to do with lazy loading remote functions which is not letting database to initialize.
[500] GET /
today at 9:32:29 PM TypeError: Cannot read properties of undefined (reading 'query')
today at 9:32:29 PM at file:///app/build/server/chunks/remote-it3q9x-BXm8oqNu.js:12579:23
today at 9:32:29 PM at Object.startActiveSpan (file:///app/build/server/chunks/remote-it3q9x-BXm8oqNu.js:546:14)
today at 9:32:29 PM at file:///app/build/server/chunks/remote-it3q9x-BXm8oqNu.js:12573:35
today at 9:32:29 PM at Object.startActiveSpan (file:///app/build/server/chunks/remote-it3q9x-BXm8oqNu.js:546:14)
today at 9:32:29 PM at NodePgPreparedQuery.execute (file:///app/build/server/chunks/remote-it3q9x-BXm8oqNu.js:12559:19)
today at 9:32:29 PM at file:///app/build/server/chunks/remote-it3q9x-BXm8oqNu.js:5005:30
today at 9:32:29 PM at Object.startActiveSpan (file:///app/build/server/chunks/remote-it3q9x-BXm8oqNu.js:546:14)
today at 9:32:29 PM at PgSelectBase.execute (file:///app/build/server/chunks/remote-it3q9x-BXm8oqNu.js:5004:19)
today at 9:32:29 PM at PgSelectBase.then (file:///app/build/server/chunks/remote-it3q9x-BXm8oqNu.js:1262:17)
I don't know why, but I'm not having this issue in dev or production. My app is also on @sveltejs/[email protected], @sveltejs/[email protected], and [email protected] (+drizzle). And my database is connecting just fine in all environments.
It looks from your system info like you might be using Bun. From my experience Bun and Sveltekit don't really work that well together. I had several issues and switched back to PNPM.
Other than that, I'm not sure.
It looks from your system info like you might be using Bun. From my experience Bun and Sveltekit don't really work that well together. I had several issues and switched back to PNPM.
We have been using Bun and SvelteKit for over two years, and it works completely without issues. 🙂 We only use it as a package manager. The runtime is Node.js v22.19.0 (LTS)
I tried switching to NPM and PNPM to test if the issue would go away, but it didn't. The only way it was resolved was by downgrading SvelteKit.
Other than that, I'm not sure.
Do you happen to have DB queries inside a handle as well? (As described in the issue)
Other than that, I'm not sure.
Do you happen to have DB queries inside a handle as well? (As described in the issue)
Yes, though not with raw SQL, I use Drizzle ORM + postgres package.
~For me the issue only happens when I run it inside docker. pnpm build && pnpm preview works fine.~
It's an existing app and everything was working smoothly before upgrading to @sveltejs/[email protected]
Edit: Just tested with pnpm build && pnpm preview now and can confirm it does not work as well. So after upgrading to @sveltejs/[email protected] apps are not able to run any database queries (using drizzle + postgres). Downgrading to @sveltejs/[email protected] fixes it.
Same'ish issue here after going from 2.38 to 2.39.1, ECONNREFUSED against localhost:
/lib/server/db/sql.ts:
import postgres from 'postgres';
import { env } from '$env/dynamic/private';
export const sql = postgres(env.POSTGRES_URL, {});
POSTGRES_URL does not point towards localhost (verified by bravely console-logging the env var right before the first usage of sql), so it seems it might be initialized before the env vars exist? Or does not get access to them?
I was having a similar issue, but I'm not sure if it is the same bug you guys are experiencing, in summary my environment variables where not being loaded, because I was using the wrong syntax. This solved my issue.
import { DB_URI } from '$env/static/private'; // <- note how it is static and not dynamic
const pool = postgres(DB_URI, { max: 1 });
export const db = drizzle(pool);
I'm saying I'm not it is the same issue because I was not able to solve it by downgrading the svelte/kit version. Hope this helps someone 👍
When I load dynamic environment variables directly within a remote function, they are undefined.
Even if I don't load them directly in the remote function, but instead via a database client (defined in src/server/db/index.ts) which uses environment variables for configuration, the issue persists.
Once this database client is used within a remote function, it seems that environment variables become unavailable globally — even in hooks.server.ts, where they are normally accessible. They are suddenly undefined as well.
This issue does not occur in @sveltejs/[email protected] — everything works fine there.
In @sveltejs/[email protected] and above, the issue only happens in production and build time (it works in development).
i created a reproduction repo
When I load dynamic environment variables directly within a remote function, they are undefined.
...
In @sveltejs/[email protected] and above, the issue only happens in production and build time (it works in development).
This is probably the root cause of why it works for me and not others. I'm using static environment variables. Something must have changed with dynamic environment variables + remote functions in 2.39.0. My guess is the lazy discovery of remote functions caused it.
Should be fixed thanks to #14441
When I load dynamic environment variables directly within a remote function, they are undefined.
Even if I don't load them directly in the remote function, but instead via a database client (defined in src/server/db/index.ts) which uses environment variables for configuration, the issue persists.
Once this database client is used within a remote function, it seems that environment variables become unavailable globally — even in hooks.server.ts, where they are normally accessible. They are suddenly undefined as well.
This issue does not occur in @sveltejs/[email protected] — everything works fine there.
In @sveltejs/[email protected] and above, the issue only happens in production and build time (it works in development).
i created a reproduction repo
Thank you. Your explanation and reproduction were very helpful.
Everyone who's facing this issue, please try updating to @sveltejs/[email protected] and report back. I'll close this issue for now
https://github.com/sveltejs/kit/releases/tag/%40sveltejs%2Fkit%402.42.1
The latest [email protected] causes a similar new issue and none of the remote functions work in production which uses database query using drizzle, everything works in dev mode.
at NodePgPreparedQuery.queryWithCache (file:///Users/ak4zh/Code/website/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected]/node_modules/drizzle-orm/pg-core/session.js:41:15)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async file:///Users/ak4zh/Code/website/node_modules/.pnpm/[email protected]_@[email protected][email protected][email protected]/node_modules/drizzle-orm/node-postgres/session.js:117:22
This appears to be happening again in the latest version of SvelteKit...
@teemingc I think this needs to be reopened?
@abdelfattahradwan Just to add I no longer have the issue. it happened once and not happening currently on my setup.
Please check the logs if the issue is same or something new.
@abdelfattahradwan Just to add I no longer have the issue. it happened once and not happening currently on my setup.
Please check the logs if the issue is same or something new.
I am currently using @sveltejs/kit:2.44.0 and the issue seems to be happening again, yes.
Can confirm it happens again on @sveltejs/kit:2.45.0
No issue in dev but only after build.
It seems the issue happens when using dynamic env variables this time. After switching my environment imports from $env/dynamic/private to $env/static/private the issue seems to resolve.
After switching my environment imports from
$env/dynamic/privateto$env/static/privatethe issue seems to resolve.
Well, that's expected. Because values from $env/static/private are injected at build time. That doesn't really "resolve" the issue when you need dynamic environment variables.