cosbgn
cosbgn
Explore posts from servers
NNuxt
Created by cosbgn on 10/9/2024 in #❓・help
Please help me understand why cloudflare can't connect to postgres on nuxt
So postgres works on cloudflare workers, but with nuxt it can't connect. My guess is that it has to do with sockets. Is there a way to debug better this error? This is a quick reproduction: Nuxt: https://github.com/cosbgn/pg-cloudflare/blob/main/server/api/test.js or: https://github.com/cosbgn/pg-cloudflare/blob/main/server/api/psql.js DB_PASSWORD: Please DM (it's a demo PSQL) Try it locally with:
NITRO_PRESET=cloudflare_module npm run build
NITRO_PRESET=cloudflare_module npm run build
and:
npx wrangler dev --remote .output/server/index.mjs --site .output/public --log-level debug
npx wrangler dev --remote .output/server/index.mjs --site .output/public --log-level debug
With just nuxt dev it works perfectly, it's only on workers that it hungs and timesout. Any help is very appreciated!
1 replies
NNuxt
Created by cosbgn on 10/8/2024 in #❓・help
Has anyone manage to connect nuxt & postgres on cloudflare?
My database always timesout on wrangler dev / or when deployed. I believe it's an issue on how nuxt deals with sockets. Did anyone manage to connect postgres?
1 replies
CDCloudflare Developers
Created by cosbgn on 10/5/2024 in #pages-help
Postgres timesout on cloudflare:
I have a PG db at digital ocean, it works perfectly in my local machine, however when deployed on cf I get: write CONNECT_TIMEOUT localhost:5432 which is weird as the port is not even 5432. This is a reprodution: https://github.com/cosbgn/pg-cloudflare/blob/main/server/api/test.js This is where it times out: https://pg-cloudflare.pages.dev/api/test Please DB me for the DB connection string and I'll share that. If someone has any idea on why it doesn't work on CF I would love it. P.s. IP are unlocked on all location.
14 replies
NNuxt
Created by cosbgn on 10/1/2024 in #❓・help
Best nitro hook to kill a DB connection?
I would like to use hyperdrive which from their docs requires to clean up the client using waitUntil:
const sql = postgres(env.HYPERDRIVE.connectionString);
const result = await sql`select * from pg_tables LIMIT 10`;
// Clean up the client, ensuring we don't kill the worker before that is
// completed.
ctx.waitUntil(sql.end());
const sql = postgres(env.HYPERDRIVE.connectionString);
const result = await sql`select * from pg_tables LIMIT 10`;
// Clean up the client, ensuring we don't kill the worker before that is
// completed.
ctx.waitUntil(sql.end());
I would like to avoid doing this in each route, so I'm thinking a plugin is the right wait, should I use afterResponse? Something like;
nitroApp.hooks.hook("afterResponse", (event, { body }) => {
// SQL is auto-exported from server/utils
event.waitUntil(sql.end());
});
nitroApp.hooks.hook("afterResponse", (event, { body }) => {
// SQL is auto-exported from server/utils
event.waitUntil(sql.end());
});
1 replies
CDCloudflare Developers
Created by cosbgn on 9/26/2024 in #pages-help
All my .env variables seem suddenly undefined. Did something change internally?
No description
22 replies
NNuxt
Created by cosbgn on 9/21/2024 in #❓・help
How would you store a ref of an external packages in a state (useState)
I have this:
import { useChat } from '@ai-sdk/vue';
const { messages, handleSubmit } = useChat()
import { useChat } from '@ai-sdk/vue';
const { messages, handleSubmit } = useChat()
handleSubmit is a method and messages is a ref(). How can I wrap this in useState to be able to call handleSubmit and access messages from any component and keep the state alive on route change?
7 replies
DTDrizzle Team
Created by cosbgn on 9/10/2024 in #help
Any way to use D1 remote DB (production one) while locally?
On wrangler is enough to add --remote but not sure how it works on drizzle
1 replies
NNuxt
Created by cosbgn on 9/5/2024 in #❓・help
Do I need to rename all template refs from `ref` to `templateRef` now with vue 3.5?
Is this needed?
2 replies
DTDrizzle Team
Created by cosbgn on 9/4/2024 in #help
generated columns reference another table
I have a table called users and another called teams. I would like to have users.plan be generated from teams.id === user.team_id and from that team get teams.plan. So pretty much user.plan is generated from the right team plan. Is this possible?
2 replies
NNuxt
Created by cosbgn on 8/30/2024 in #❓・help
fetch full screen error on production
I use a custom fetch:
export const $api = $fetch.create({
async onResponseError({ response }) {
const possibilities = [response?._data?.statusMessage, response?.error?.data?.statusMessage, response?._data?.message, response.message, response?.statusText, "Unknown Server Error"]
const withData = possibilities.filter(f => f?.length)
const err_msg = `${response.status}: ${withData[0]}`
if (import.meta.browser){
toast(err_msg, "error")
} else {
console.error(err_msg)
}
}
})
export const $api = $fetch.create({
async onResponseError({ response }) {
const possibilities = [response?._data?.statusMessage, response?.error?.data?.statusMessage, response?._data?.message, response.message, response?.statusText, "Unknown Server Error"]
const withData = possibilities.filter(f => f?.length)
const err_msg = `${response.status}: ${withData[0]}`
if (import.meta.browser){
toast(err_msg, "error")
} else {
console.error(err_msg)
}
}
})
This works super well on dev, when an error shows it simply shows the toast. On production instead it shows the toast but also the full screen nuxt-error. How can I get that fixed?
1 replies
CDCloudflare Developers
Created by cosbgn on 8/16/2024 in #pages-help
Is there any way to access a pages deployment without passing first from the cloudflare CDN?
My issue is that the cloudflare CDN has a 100 second timeout and I need a long running backend task. Pages doesn't support crons or queues, so I can rely on an external cron tool, but I would need to connect directly to the worker skipping the CDN
4 replies
CDCloudflare Developers
Created by cosbgn on 8/5/2024 in #pages-help
Is there any workarount to get Cron Triggers or bckground tasks to work on pages?
I'm very limited by pages for their 100second timeout and absence of queues, crons, etc. How does everyone deals with longer tasks on pages?
2 replies
DTDrizzle Team
Created by cosbgn on 7/7/2024 in #help
ERROR [unhandledRejection] connect ECONNREFUSED 127.0.0.1:60589
I use a drizzle-http-sqlite proxy to connect to my remote D1. After a while it hungs with this error. My issue is that I'm not connecting to a localhost so I have no idea why it happens. This is my proxy:
import { drizzle as drizzleProxy } from 'drizzle-orm/sqlite-proxy';

return drizzleProxy(async (sql, params, method) => {
const url = `https://api.cloudflare.com/client/v4/accounts/${process.env.ACCOUNT_ID}/d1/database/${process.env.D1_ID}/query`
const data = await $fetch(url, {
method: 'POST',
headers: { Authorization: `Bearer ${process.env.TOKEN}`, 'Content-Type': 'application/json' },
body: { sql, params, method }
})
if (data?.errors?.length > 0 || !data?.success) {
throw new Error(`Error from sqlite proxy server: \n${JSON.stringify(data)}}`)
}
const qResult = data.result[0]
if (!qResult?.success) {
throw new Error(`Error from sqlite proxy server: \n${JSON.stringify(data)}`)
}
return { rows: qResult.results.map(r => Object.values(r)) }
})
import { drizzle as drizzleProxy } from 'drizzle-orm/sqlite-proxy';

return drizzleProxy(async (sql, params, method) => {
const url = `https://api.cloudflare.com/client/v4/accounts/${process.env.ACCOUNT_ID}/d1/database/${process.env.D1_ID}/query`
const data = await $fetch(url, {
method: 'POST',
headers: { Authorization: `Bearer ${process.env.TOKEN}`, 'Content-Type': 'application/json' },
body: { sql, params, method }
})
if (data?.errors?.length > 0 || !data?.success) {
throw new Error(`Error from sqlite proxy server: \n${JSON.stringify(data)}}`)
}
const qResult = data.result[0]
if (!qResult?.success) {
throw new Error(`Error from sqlite proxy server: \n${JSON.stringify(data)}`)
}
return { rows: qResult.results.map(r => Object.values(r)) }
})
1 replies
DTDrizzle Team
Created by cosbgn on 7/5/2024 in #help
D1_ERROR: near "in": syntax error at offset 153
I can't seem to use inArray with d1:
D1_ERROR: near "in": syntax error at offset 153
D1_ERROR: near "in": syntax error at offset 153
With
const result = await db
.select()
.from(posts)
.where(
and(
inArray(posts.content, ["book"] ),
eq(posts.isActive, true)
)
)
const result = await db
.select()
.from(posts)
.where(
and(
inArray(posts.content, ["book"] ),
eq(posts.isActive, true)
)
)
Any suggestions?
2 replies
NNuxt
Created by cosbgn on 7/4/2024 in #❓・help
Is there an easy way to get `event`?
I use drizzle and cloudflare so I have an util like this one:
export const useDb = (event) => drizzle(event.context.cloudflare.env.DB, { schema })
export const useDb = (event) => drizzle(event.context.cloudflare.env.DB, { schema })
My issue is that I need always event and it's annoying to pass it around betwen functions. I know there is useEvent() but it requires an experimental asyncContext which is not available on cloudflare. How is everyone solving this?
8 replies
NNuxt
Created by cosbgn on 6/1/2024 in #❓・help
Props based on route generate hydration missmatch
// /pages/tools/[tool_slug].vue
<template>
<div>
<tool :config="tools[tool_slug]" />
</div>
</template>
<script setup>
import tools from '~/assets/templates/en.json'
const route = useRoute()
const { tool_slug } = route.params
if (!tools?.[tool_slug]?.title) {
throw createError({ statusCode:404, statusMessage:"Tool not found" })
}
</script>
// /pages/tools/[tool_slug].vue
<template>
<div>
<tool :config="tools[tool_slug]" />
</div>
</template>
<script setup>
import tools from '~/assets/templates/en.json'
const route = useRoute()
const { tool_slug } = route.params
if (!tools?.[tool_slug]?.title) {
throw createError({ statusCode:404, statusMessage:"Tool not found" })
}
</script>
I want to do something like the above. My issue is that I get a missmatch because confi is empty on server and filled in client. Is there a way to have it filled also on server?
8 replies
NNuxt
Created by cosbgn on 5/24/2024 in #❓・help
get `event` in `/utils/db.js` - Can I be done?
I would like to do something like this:
// utils/db.js
import { drizzle } from 'drizzle-orm/d1';
import * as schema_file from "../db/schema.js";

let cached_db = null

export const useDb = () => {
if (!cached_db) {
const event = useRequestEvent()
cached_db = drizzle(event.context.cloudflare.env.D1_PROD_BINDING, { schema: schema_file })
}
return cached_db
}

export const db = useDb()
export const schema = schema_file
// utils/db.js
import { drizzle } from 'drizzle-orm/d1';
import * as schema_file from "../db/schema.js";

let cached_db = null

export const useDb = () => {
if (!cached_db) {
const event = useRequestEvent()
cached_db = drizzle(event.context.cloudflare.env.D1_PROD_BINDING, { schema: schema_file })
}
return cached_db
}

export const db = useDb()
export const schema = schema_file
So then in any route I can do db.select() - However useRequestEvent() is not defined somehow? I know I can simply pass const db = useDb(event) on top of each route, I just would like to avoid passing event on every route and hopefully get better types. Should this instead be a plugin? What's the best practice here?
2 replies
NNuxt
Created by cosbgn on 5/3/2024 in #❓・help
Did anyone manage to handle CORS with h3/nuxt/nitro?
I'm trying everything like this:
export default defineEventHandler( async (event) => {
const cors_headers = {
origin: '*',
preflight: { statusCode: 204 },
methods: '*'
}
await handleCors(event, cors_headers)
await appendCorsHeaders(event, cors_headers)
await appendResponseHeaders(event, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, HEAD, POST, OPTIONS",
"Access-Control-Allow-Headers": "*"
})
return "hello"
})
export default defineEventHandler( async (event) => {
const cors_headers = {
origin: '*',
preflight: { statusCode: 204 },
methods: '*'
}
await handleCors(event, cors_headers)
await appendCorsHeaders(event, cors_headers)
await appendResponseHeaders(event, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, HEAD, POST, OPTIONS",
"Access-Control-Allow-Headers": "*"
})
return "hello"
})
I always get: request blocked: (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
15 replies
DTDrizzle Team
Created by cosbgn on 4/18/2024 in #help
Cannot read properties of null (reading 'dialect')
await migrate(db, { migrationsFolder: "server/db/migrations" }) is failing. I'm using d1. What could be the issue?
1 replies
CDCloudflare Developers
Created by cosbgn on 4/10/2024 in #pages-help
Mailchannels: sender is not authorized
I'm getting:
0 "Failed to send email: 550 5.7.1 This sender is not authorized to send from my-site.com. See https://bit.ly/domain-lockdown. cfid=my-site-v3.pages.dev"
0 "Failed to send email: 550 5.7.1 This sender is not authorized to send from my-site.com. See https://bit.ly/domain-lockdown. cfid=my-site-v3.pages.dev"
I have a TXT record with: name: _mailchannels
value: =mc1 cfid=my-site-v3.pages.dev (copied as is from error message) --- Do I need to just wait for DNS to catch up, or am I missing something?
6 replies