N
Nuxt2mo ago
KWAC

nuxt 3 + cloudfare D1 problems with env.d.ts file

I'm using nuxt 3 with cloudfare D1, but I have encountered some problems. It seems that it cannot read env.d.ts file I have created. I'm getting this error:
500 Cannot read properties of undefined (reading 'env')
500 Cannot read properties of undefined (reading 'env')
I used this repo: https://github.com/tlebeitsuk/nuxt-cloudflare-lucia My configured env.d.ts file:
import { CfProperties, Request, ExecutionContext, KVNamespace, D1Database } from '@cloudflare/workers-types';

declare module 'h3' {
interface H3EventContext {
cf: CfProperties,
cloudflare: {
request: Request,
env: {
MY_KV: KVNamespace,
DB: D1Database,
}
context: ExecutionContext,
};
}
}
import { CfProperties, Request, ExecutionContext, KVNamespace, D1Database } from '@cloudflare/workers-types';

declare module 'h3' {
interface H3EventContext {
cf: CfProperties,
cloudflare: {
request: Request,
env: {
MY_KV: KVNamespace,
DB: D1Database,
}
context: ExecutionContext,
};
}
}
GitHub
GitHub - tlebeitsuk/nuxt-cloudflare-lucia: A demo using Nuxt, Cloud...
A demo using Nuxt, Cloudflare Pages, Cloudflare D1 database and Lucia for auth - tlebeitsuk/nuxt-cloudflare-lucia
12 Replies
KWAC
KWAC2mo ago
And here is middleware->auth.ts
import { verifyRequestOrigin } from "lucia"
import { initializeLucia } from "../utils/auth"
import type { User, Session } from "lucia"

let lucia: ReturnType<typeof initializeLucia>

export default defineEventHandler(async (event) => {
// CSRF protection
if (!isMethod(event, "GET")) {
const originHeader = getHeader(event, "Origin") ?? null
const hostHeader = getHeader(event, "Host") ?? null
if (
!originHeader ||
!hostHeader ||
!verifyRequestOrigin(originHeader, [hostHeader])
) {
return sendNoContent(event, 403)
}
}



const { DB } = event.context.cloudflare.env

if (!lucia) {
lucia = initializeLucia(DB)
}

event.context.lucia = lucia


const sessionId = getCookie(event, lucia.sessionCookieName) ?? null
if (!sessionId) {
event.context.session = null
event.context.user = null
return
}

const { session, user } = await lucia.validateSession(sessionId)
if (session && session.fresh) {
appendResponseHeader(
event,
"Set-Cookie",
lucia.createSessionCookie(session.id).serialize()
)
}
if (!session) {
appendResponseHeader(
event,
"Set-Cookie",
lucia.createBlankSessionCookie().serialize()
)
}

event.context.session = session
event.context.user = user
})

declare module "h3" {
interface H3EventContext {
user: User | null
session: Session | null
lucia: ReturnType<typeof initializeLucia>
}
}
import { verifyRequestOrigin } from "lucia"
import { initializeLucia } from "../utils/auth"
import type { User, Session } from "lucia"

let lucia: ReturnType<typeof initializeLucia>

export default defineEventHandler(async (event) => {
// CSRF protection
if (!isMethod(event, "GET")) {
const originHeader = getHeader(event, "Origin") ?? null
const hostHeader = getHeader(event, "Host") ?? null
if (
!originHeader ||
!hostHeader ||
!verifyRequestOrigin(originHeader, [hostHeader])
) {
return sendNoContent(event, 403)
}
}



const { DB } = event.context.cloudflare.env

if (!lucia) {
lucia = initializeLucia(DB)
}

event.context.lucia = lucia


const sessionId = getCookie(event, lucia.sessionCookieName) ?? null
if (!sessionId) {
event.context.session = null
event.context.user = null
return
}

const { session, user } = await lucia.validateSession(sessionId)
if (session && session.fresh) {
appendResponseHeader(
event,
"Set-Cookie",
lucia.createSessionCookie(session.id).serialize()
)
}
if (!session) {
appendResponseHeader(
event,
"Set-Cookie",
lucia.createBlankSessionCookie().serialize()
)
}

event.context.session = session
event.context.user = user
})

declare module "h3" {
interface H3EventContext {
user: User | null
session: Session | null
lucia: ReturnType<typeof initializeLucia>
}
}
Specifically this part
js const { DB } = event.context.cloudflare.env
js const { DB } = event.context.cloudflare.env
is responsible am i doing something wrong
Oreki
Oreki2mo ago
Hii, were you able to fix this error? if i call my route directly, it returns data successfully, no idea why this would fail
KWAC
KWAC2mo ago
eh unfortunately not, i'm still trying to figure out what could be wrong
Oreki
Oreki2mo ago
this went away for me once i created a types folder and added env.d.ts
KWAC
KWAC2mo ago
could you share a repo so i could take a look?
Oreki
Oreki2mo ago
Mine's not public, but here's how the structure looks like
apps/
website/
nuxt.config.ts
(...)
src/
types/
env.d.ts
(...)
apps/
website/
nuxt.config.ts
(...)
src/
types/
env.d.ts
(...)
// env.d.ts

import { CfProperties, Request, ExecutionContext } from '@cloudflare/workers-types';

declare module 'h3' {
interface H3EventContext {
cf: CfProperties,
cloudflare: {
request: Request,
env: Record<string, string>,
context: ExecutionContext,
};
}
}
// env.d.ts

import { CfProperties, Request, ExecutionContext } from '@cloudflare/workers-types';

declare module 'h3' {
interface H3EventContext {
cf: CfProperties,
cloudflare: {
request: Request,
env: Record<string, string>,
context: ExecutionContext,
};
}
}
this basically worked for me
KWAC
KWAC2mo ago
env.d.ts specifically needs to be in src->types folder? I thought i can paste this file in root folder of the project
Oreki
Oreki2mo ago
if you have src set in nuxt config then it has to go inside src yes that is what i believe lol i am new to nuxt/vue as well so not sure
KWAC
KWAC2mo ago
Okay But looking at this import { CfProperties, Request, ExecutionContext, KVNamespace, D1Database } from '@cloudflare/workers-types'; declare module 'h3' { interface H3EventContext { cf: CfProperties, cloudflare: { request: Request, env: { MY_KV: KVNamespace, DB: D1Database, } context: ExecutionContext, }; } } am I declaring DB correctly?
DB: D1Database
DB: D1Database
And for MY_KV: KVNamespace is not needed in my case? As for now I only need D1
Oreki
Oreki2mo ago
that is how'd you declare normally when using cloudflare workers so unless nitro does something with the variables, this should work Also this randomly still appears for me
KWAC
KWAC2mo ago
@Oreki Sorry for pinging I now setup it correctly using command
npm create cloudflare@latest my-nuxt-app -- --framework=nuxt
npm create cloudflare@latest my-nuxt-app -- --framework=nuxt
I was missing some files like
worker-configuration.d
worker-configuration.d
Also I had to downgrade wrangler version because newer one was broken. My drizzle config looks like this:
import { defineConfig } from "drizzle-kit"

export default defineConfig({
dialect: 'sqlite',
schema: './server/db/schema.ts',
out: './server/db/migrations',
driver: 'd1-http',
dbCredentials: {
accountId: 'xxx',
databaseId: 'xxx',
token: 'xxx'
}
})
import { defineConfig } from "drizzle-kit"

export default defineConfig({
dialect: 'sqlite',
schema: './server/db/schema.ts',
out: './server/db/migrations',
driver: 'd1-http',
dbCredentials: {
accountId: 'xxx',
databaseId: 'xxx',
token: 'xxx'
}
})
My question is how to query and receive data from a table? Mine doesn't really work. I have two entries in that table. It shows status 200 but it doens't really print out that info from table getdata.js
import { defineEventHandler } from 'h3'
import { users } from '@/server/db/schema'
import { eq } from 'drizzle-orm'

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

try {

const allUsers = await db.select().from(users).all()
console.log('All Users:', allUsers)


return allUsers
} catch (error) {
// Handle any errors that might occur
console.error('Error retrieving users:', error) // Log the error message
throw createError({
statusCode: 500,
statusMessage: 'Internal Server Error'
})
}
})
import { defineEventHandler } from 'h3'
import { users } from '@/server/db/schema'
import { eq } from 'drizzle-orm'

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

try {

const allUsers = await db.select().from(users).all()
console.log('All Users:', allUsers)


return allUsers
} catch (error) {
// Handle any errors that might occur
console.error('Error retrieving users:', error) // Log the error message
throw createError({
statusCode: 500,
statusMessage: 'Internal Server Error'
})
}
})
Oreki
Oreki2mo ago
i don't really think nitro would have a db key in context?
Want results from more Discord servers?
Add your server