Postgresql Connection (Node) erroring: No such module "cloudflare:sockets".
I've been trying to test out a CF worker with a basic DB connection and query and tried everything to debug it without any luck. I have:
Node - v21.6.1
In my wrangler.toml:
node_compat = true
I installed 'pg' and have the newest version which should work with CF workers.
Here's the basic JS I'm trying to use to connect:
import { Client } from 'pg';
import { Client } from 'pg';
async function handleRequest(request) {
let client = null;
try {
client = new Client(DB_URL);
await client.connect();
const result = await client.query('SELECT * FROM TABLENAME');
return new Response(JSON.stringify(result.rows), {
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
console.error('Database connection error:', error);
return new Response(JSON.stringify({ error: error.message }), {
headers: { 'Content-Type': 'application/json' },
status: 500,
});
} finally {
if (client) {
try {
await client.end();
} catch (err) {
console.error('Failed to close database connection:', err);
}
}
}
}
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});
Here's my tail log:
GET https://worker.barrett-2ac.workers.dev/favicon.ico - Ok @ 4/17/2024, 11:18:55 AM
(error) Database connection error: Error: No such module "cloudflare:sockets".
(error) Failed to close database connection: TypeError: Cannot read properties of null (reading 'close')
https://worker.barrett-2ac.workers.dev
I'd love any ideas or things I can try to debug. I'm hitting a wall as I can't find a ton of documentation on this online. It is a Digital Ocean Postgresql db requiring SSL, which I configured, and I think the error would differ if that was it, but I'm not too sure.
10 Replies
here is my setup work with CF Worker:
import { Hono } from "hono";
import pkg from "pg";
const app = new Hono();
const { Pool } = pkg;
const connectionString = "xxxxxxxxxxxxxxxxxxxxxxxx";
app.post("/users", async (c) => {
const { email, id, name } = await c.req.json();
const pool = new Pool({ connectionString });
try {
const res = await pool.query(
INSERT INTO "User" (id, email, name)
VALUES
($1, $2, $3),
[id, email, name]
);
return c.json(res.rows);
} catch (err) {
console.error("Error executing query:", err);
return c.text("Errors!!!!!!");
} finally {
await pool.end();
}
});
export default app;
my packgae.json: "pg": "^8.11.3", "hono": "^4.1.3",
wrangler:toml : name = "my-app"
compatibility_date = "2024-03-29"
main = "src/index.mjs"
minify = true
compatibility_flags = [ "nodejs_compat" ]
I think the issue in your code is "node_compat = true", just use compatibility_flags = [ "nodejs_compat" ] instead.@thanhle thank you! When I've tried:
compatibility_flags = [ "nodejs_compat" ]
I just get hit with like 20 errors all related to the 'pg' module.
✘ [ERROR] Build failed with 22 errors:
node_modules/pg-cloudflare/dist/index.js:1:29: ERROR: Could not resolve "events"
node_modules/pg-connection-string/index.js:76:77: ERROR: Could not resolve "fs"
node_modules/pg-pool/index.js:2:29: ERROR: Could not resolve "events"
node_modules/pg/lib/client.js:3:27: ERROR: Could not resolve "events"
node_modules/pg/lib/connection-parameters.js:3:18: ERROR: Could not resolve "dns"
...
I don't have pg-cloudflare in my package.json but I guess it's being installed by pg.
"pg": "^8.11.5"
can you share your package,json
@thanhle
{
"name": "worker",
"version": "0.0.0",
"private": true,
"scripts": {
"deploy": "wrangler deploy",
"dev": "wrangler dev",
"start": "wrangler dev"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20240405.0",
"typescript": "^5.0.4",
"wrangler": "^3.0.0"
},
"dependencies": {
"pg": "^8.11.5"
}
}
How do you deploy your worker? By wrangler?
@thanhle yup
I tried both deploying and dev, same issue with both
can you make a reprocude with github
small git is ok
I just tried the tutorial over again to rule out anything weird I did and the same sockets error. https://github.com/shepherdindustries/CFWorkerTest
GitHub
GitHub - shepherdindustries/CFWorkerTest
Contribute to shepherdindustries/CFWorkerTest development by creating an account on GitHub.
You just need to set the secret to DB_URL
Do you think it's possibly just an auth issue with my postgres db and it's just returning that error? I can't find anything online.
dont worry I will try and let you know immediately. i will test with my database url (that I knew it should work)
this works for me: just change with your databaseurl and see: import pkg from "pg";
const { Pool } = pkg;
export default {
async fetch(request, env, ctx) {
const connectionString =
"postgresql://xxxxxxxxx:xxxxxxxxxxx@xxxxxxxxxxxxx:xxxxxxxxxx/xxxxxxxxxxxxxx?ssl=true";
let pool = null;
try {
pool = new Pool({ connectionString });
const result = await pool.query('SELECT * FROM "Message"');
return new Response(JSON.stringify(result.rows), {
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("Database connection error:", error);
return new Response(JSON.stringify({ error: error.message }), {
headers: { "Content-Type": "application/json" },
status: 500,
});
} finally {
if (pool) {
try {
await pool.end();
} catch (err) {
console.error("Failed to close database connection:", err);
}
}
}
},
};
i try to use Client instead of Pool but Client did not work in my case. dont know the issue?