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’)
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,
};
}
}
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>
}
}
Specifically this part const { DB } = event.context.cloudflare.env
is responsible