Drizzle / useFetch / cloudflare error on deployment

Hi, When I deploy my app to cloudflare, I get a 500 error when retrieving data from my database on initial load, if I use the refresh method to get the data again it works fine. Locally works fine on page load. This is how I am using drizzle: server/api/users.get.ts:
import { users } from '../db/schema'
import { useDatabase } from '../utils/db'

export default defineEventHandler(async (event) => {
const db = useDatabase(event)

const existingUsers = await db.select().from(users)

if (existingUsers.length < 1) {
await db.insert(users).values({ email: '[email protected]' })
}

return await db.select({ email: users.email}).from(users)
})
import { users } from '../db/schema'
import { useDatabase } from '../utils/db'

export default defineEventHandler(async (event) => {
const db = useDatabase(event)

const existingUsers = await db.select().from(users)

if (existingUsers.length < 1) {
await db.insert(users).values({ email: '[email protected]' })
}

return await db.select({ email: users.email}).from(users)
})
useDatabase helper:
import { drizzle } from 'drizzle-orm/d1'
import type { H3Event } from 'h3'

export function useDatabase(event: H3Event) {
return drizzle(event.context.cloudflare.env.DB)
}
import { drizzle } from 'drizzle-orm/d1'
import type { H3Event } from 'h3'

export function useDatabase(event: H3Event) {
return drizzle(event.context.cloudflare.env.DB)
}
app.vue:
<script setup lang="ts">
const { data, error, refresh } = useFetch("/api/users");
</script>

<template>
<div>
<NuxtRouteAnnouncer />
{{ data }}

<div v-if="error">{{ error }}</div>

<button @click="refresh">Refresh</button>
</div>
</template>
<script setup lang="ts">
const { data, error, refresh } = useFetch("/api/users");
</script>

<template>
<div>
<NuxtRouteAnnouncer />
{{ data }}

<div v-if="error">{{ error }}</div>

<button @click="refresh">Refresh</button>
</div>
</template>
My question is - what am I doing wrong?
3 Replies
kapa.ai
kapa.ai2w ago
Hi @BiffBaffBoff. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Based on the information provided in the knowledge sources, I can identify a few potential issues with your Cloudflare deployment and useFetch implementation. The Issue You're experiencing a 500 error on initial page load when deployed to Cloudflare, but subsequent refreshes using the refresh() method work fine. This suggests a caching or initialization issue with useFetch in the Cloudflare environment. Possible Causes and Solutions 1. useFetch Caching Behavior The useFetch composable in Nuxt 3 caches responses, including error responses. This is a known issue that was fixed in Nuxt 3.8.1:
It is an error from the framework. Fix in Nuxt 3.8.1 GitHub PR #23889 and #23797
If you're using a version prior to 3.8.1, consider upgrading your Nuxt version. 2. Cloudflare Initialization Timing When deploying to Cloudflare, there might be timing issues with how the D1 database is initialized. The error on initial load but success on refresh suggests that the database connection might not be fully established on the first request. Try adding a key to your useFetch call to prevent caching:
<script setup lang="ts">
const { data, error, refresh } = useFetch("/api/users", {
key: Date.now().toString() // Force a new request each time
});
</script>
<script setup lang="ts">
const { data, error, refresh } = useFetch("/api/users", {
key: Date.now().toString() // Force a new request each time
});
</script>
This approach has helped others with similar issues:
Try adding a key value inside useFetch's options object with an unique value every time (so for example based on Date.now()). That's what helped me with similar issue. Otherwise useFetch tends to cache data and won't re-fetch when it thinks it is the same API call. Stack Overflow
3. Cloudflare Configuration Ensure your Cloudflare configuration is correct: 1. Make sure your D1 database is properly bound to your Cloudflare Pages project with the binding name DB as you're using in your code. 2. Check that you're using the correct build preset for Cloudflare Pages:
nuxi build --preset=cloudflare_pages
nuxi build --preset=cloudflare_pages
Or in your nuxt.config.ts:
export default defineNuxtConfig({
nitro: {
preset: 'cloudflare_pages',
},
});
export default defineNuxtConfig({
nitro: {
preset: 'cloudflare_pages',
},
});
As mentioned in the Cloudflare Pages deployment documentation. 4. Cloudflare CDN Settings If you're using Cloudflare's CDN features, certain settings might interfere with your Nuxt application: Make sure these options are disabled in Cloudflare: - "Rocket Loader™" - "Mirage" - "Email Address Obfuscation" As noted in the Nuxt deployment documentation. Alternative Approach If you're still facing issues, consider using $fetch instead of useFetch for your client-side operations:
<script setup lang="ts">
const data = ref(null)
const error = ref(null)

const fetchData = async () => {
try {
data.value = await $fetch("/api/users")
error.value = null
} catch (err) {
error.value = err
}
}

// Initial fetch
fetchData()

// Refresh function
const refresh = () => fetchData()
</script>
<script setup lang="ts">
const data = ref(null)
const error = ref(null)

const fetchData = async () => {
try {
data.value = await $fetch("/api/users")
error.value = null
} catch (err) {
error.value = err
}
}

// Initial fetch
fetchData()

// Refresh function
const refresh = () => fetchData()
</script>
This approach is recommended for POST requests according to the Nuxt documentation, but it can also help with GET requests that are having caching issues. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2w ago
<@337685335205085196> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
BiffBaffBoff
BiffBaffBoffOP2w ago
I'm using nuxt 3.16.2 (the latest version, I used npm create cloudflare@latest spot-tube -- --framework=nuxt --platform=pages to get started so all the cloudflare config is set appropriately

Did you find this page helpful?