Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimal Sveltekit + pg integration fails with "status" error

I'm trying to get Postgres working with sveltekit and a very minimal example is giving me issues. This is probably a configuration thing but the error I'm getting back from sveltekit makes no sense to me.

I start by installing a new project:

npm create svelte@latest my-testapp

Then I install "pg" to get Postgres pooling:

npm i pg

Then I add a page under src/lib/db.js:

import { Client, Pool } from 'pg';
const pool = new Pool({
    user: 'xxx',
    host: 'xxx',
    database: 'xxx',
    password: 'xxx',
    port: 5432,
})
export const connectToDB = async () => await pool.connect();

Finally I add src/hooks.server.js to give me access to the pool within routes:

import { connectToDB } from '$lib/db';

export const handle = async ({event, resolve}) => {
    const dbconn = await connectToDB();
    event.locals = { dbconn };
    const response = await resolve(event);
    dbconn.release();
}

The server fails to compile with a couple of these errors:

Cannot read properties of undefined (reading 'status')
TypeError: Cannot read properties of undefined (reading 'status')
    at respond (file:///C:/Users/user/code/svelte/my-testapp/node_modules/@sveltejs/kit/src/runtime/server/index.js:314:16)
    at async file:///C:/Users/user/code/svelte/my-testapp/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:406:22

Not sure where "status" is coming from, seems to be part of the initial scaffolding. Any help appreciated.

Also - if there is a more straightforward way to integrate pg with sveltekit then I'm happy to hear about it. Thanks

like image 597
user7654493 Avatar asked Sep 19 '25 16:09

user7654493


1 Answers

My bad - the hooks function wasn't returning the response.

Hooks.server.js should read:

import { connectToDB } from '$lib/db';

export const handle = async ({event, resolve}) => {
    const dbconn = await connectToDB();
    event.locals = { dbconn };
    const response = await resolve(event);
    dbconn.release();
    return response
}
like image 179
user7654493 Avatar answered Sep 22 '25 10:09

user7654493