Next.js Discord

Discord Forum

[ERROR] When I Connect postgresql and query in multiple different scripts

Answered
Asian black bear posted this in #help-forum
Open in Discord
Avatar
Asian black bearOP
I'm tryin to make one file that connects to the database then import just the connection to the scripts I need to do anything with the database like queries.

connect.js
`use server`;
import { Client } from 'pg';
import db from 'dbDetails.js';




var client = () => {

    client = new Client(db);
   return client.connect();
}
export default client;


but whenever I try to imported I get this error

[ Server ] Error: {imported module [project]/clientConn.js [app-rsc] (ecmascript)}.default.query is not a function


how to do it right ?
Answered by Alfonsus Ardani
try

import { Client } from 'pg';
import db from 'dbDetails.js';

var client = new Client(db);
return client.connect();

export default client;
View full answer

70 Replies

Avatar
Asian black bearOP
also please tell me if that's the right approach
Avatar
Asian black bearOP
up
up
Avatar
I'm tryin to make one file that connects to the database then import just the connection to the scripts I need to do anything with the database like queries.

Can you try removing 'use server' and importing it in a server component to see if it works?
is this the right approach ?
Avatar
we will see in a moment
Avatar
@Alfonsus Ardani you declared `client` as a function, and inside you declared `client` as new Client(db)
Avatar
Asian black bearOP
`use server`;
import { Client } from 'pg';
import db from 'dbDetails.js';
var xx = () => { return Client(db).connect();}
export default xx;

same error
Avatar
remove 'use server'
Avatar
Asian black bearOP
ok
Avatar
@Alfonsus Ardani remove 'use server'
Avatar
Asian black bearOP
that made no difference
Avatar
something wrong with
import db from 'dbDetails.js';
then
are you using typescript?
Avatar
Asian black bearOP
not really because I used to connect on the same script using import db from 'dbDetails.js'; and it worked, I can query normally if Im connecting the client on the same script but if I'm importing it, it doesnt work.
Avatar
@Alfonsus Ardani are you using typescript?
Avatar
Asian black bearOP
yes I think i have .ts formates
im following a toturial im new to react and nextJS
Avatar
Asian black bearOP
sure
Image
im using VS 2019
they are using '@vercel/postgres'; but Im hosting pg locally
Avatar
im interested to know if your project is using typescript or javascript
i dont think you can mix it up
Avatar
try

import { Client } from 'pg';
import db from 'dbDetails.js';

var client = new Client(db);
return client.connect();

export default client;
Answer
Avatar
@Alfonsus Ardani try tsx import { Client } from 'pg'; import db from 'dbDetails.js'; var client = new Client(db); return client.connect(); export default client;
Avatar
Asian black bearOP
[ Server ] Error: Cannot access '{default export}' before initialization
sorry for the delay i have a 1 yearsOld child
Avatar
@Asian black bear sorry for the delay i have a 1 yearsOld child
Avatar
its fine, how are they? i hope they are healthy
Avatar
@Alfonsus Ardani its fine, how are they? i hope they are healthy
Avatar
Asian black bearOP
thank u that is very sweet, yes they are 🙂
Avatar
@Alfonsus Ardani can we see `dbDetails.js` ?
Avatar
Asian black bearOP
sure its pretty basic
const { Client } = require('pg');

const db = new Client({
    user: 'user1',
    host: 'localhost',
    database: 'nextJSdb',
    password: "123456",
    port: 5332,
});
export default db ;
Avatar
is it a typescript file or a javascript file?
is your project using typescript or no typescript?
Avatar
@Alfonsus Ardani is it a typescript file or a javascript file?
Avatar
Asian black bearOP
im sorry how to know this ?
im new
Avatar
check the name of the file
Avatar
Asian black bearOP
its a js file
Avatar
i see
Im not sure why its wrong
do you have a github repository?
Avatar
Asian black bearOP
nope
its kinda odd, why can i just pass it
i've also noticed that db itself is Client
Avatar
yeah
Avatar
Asian black bearOP
so db.connect() should be fine right ?
Avatar
yeah\
Avatar
Asian black bearOP
Im so sorry for the delay again - its impossible to control a 1yearOld
-------------------
SUMMERY:
--------------------
so basically, I have 2 .ts scripts that attempts to connect to the database for two different reasons
dbDetails.js
const { Client } = require('pg');

const db = new Client({
    user: 'user1',
    host: 'localhost',
    database: 'nextJSdb',
    password: "123456",
    port: 5332,
});
export default db ;


and then the other two ts files connect to it the same way
import { Client } from 'pg';
import db from 'dbDetails';

  const client:Client = new Client(db);
  client.connect().catch(err => console.error('Failed to connect to the db [ERROR]: ', err));


this code works will when only 1 file is connected when I connect the other file I get an error

Failed to connect to the db [ERROR]:  [AggregateError: ] { code: 'ECANCELED' }
I've also tried to make and export client as mentioned above and import it in the two ts files
import { Client } from 'pg';
import db from 'dbDetails.js';

var client = new Client(db);
return client.connect();

export default client;

but again it rose an error [ Server ] Error: Cannot access '{default export}' before initialization
I've tried many things none of them worked
Avatar
Yacare Caiman
this is how you connect to with pg import pg from "pg"; export const pool = new pg.Pool({ host: process.env.PG_HOST, user: process.env.PG_USER, password: process.env.PG_PASSWORD, port: 5432 || process.env.PG_PORT, database: process.env.PG_DATABASE, idleTimeoutMillis: 30000, ssl: { rejectUnauthorized: false } });
and futher
const client = await pool.connect();
const result = await client.query(SELECT * Users;,[]);
more specifically const query = "SELECT * FROM users WHERE id = $1 AND email = $2;"; const values = [123, "test@example.com"];
Avatar
@Alfonsus Ardani try tsx import { Client } from 'pg'; import db from 'dbDetails.js'; var client = new Client(db); return client.connect(); export default client;
Avatar
Asian black bearOP
I finally got it to work
const client = new Client(db);
client.connect();
export default client;

I have no idea why it didnt work bk then maybe the error was caused by something else
Avatar
Yacare Caiman
Client makes new req each time when u query data base. And create lot of connections
Pool re-use the previous connections
Avatar
@Yacare Caiman Pool re-use the previous connections
Avatar
Yacare Caiman
If connections exist
Avatar
@Yacare Caiman If connections exist
Avatar
Asian black bearOP
I love this ofc!
are all connections session based?
sorry for asking too many questions, Im new to react and nextJS
Avatar
@Asian black bear I love this ofc! are all connections session based?
Avatar
Yacare Caiman
Yes, both client and Pool connections are session based!