Can you extend H3EventContext?

I'm trying to type my context correctly so it can be used inside defineEventHandler() like this:
// file: /server/api/somefile.ts
export default defineEventHandler(async function(event) {
const context = event.context as Context;
...
})
// file: /server/api/somefile.ts
export default defineEventHandler(async function(event) {
const context = event.context as Context;
...
})
I'm trying to extend H3EventContext like this:
// file: /server/graphql/context.ts
export default class Context extends H3EventContext {
constructor(event: H3Event) {
this.user = event.context.user
}

user: any
}
// file: /server/graphql/context.ts
export default class Context extends H3EventContext {
constructor(event: H3Event) {
this.user = event.context.user
}

user: any
}
However, the type H3EventContext seems not to exist anywhere (import { H3EventHandler } from 'h3' doesn't work). Now, I found this issue that seems to be solved: https://github.com/unjs/h3/issues/122, but I don't understand how this works at all. I've tried to add this to /server/graphql/context.ts:
import {type NodeIncomingMessage, type NodeServerResponse, type H3Event} from 'h3'
declare module 'h3' {
interface CompatibilityEvent {
'__is_event__': true;
event: H3Event;
req: NodeIncomingMessage;
res: NodeServerResponse;
context: Context;
}
}
import {type NodeIncomingMessage, type NodeServerResponse, type H3Event} from 'h3'
declare module 'h3' {
interface CompatibilityEvent {
'__is_event__': true;
event: H3Event;
req: NodeIncomingMessage;
res: NodeServerResponse;
context: Context;
}
}
But this does not seem to fix anything.
GitHub
Issues · unjs/h3
⚡️ Minimal H(TTP) framework built for high performance and portability - Issues · unjs/h3
2 Replies
Gerbuuun
Gerbuuun4mo ago
You should do it like this:
declare module 'h3' {
interface H3EventContext {
// your types here
}
}
declare module 'h3' {
interface H3EventContext {
// your types here
}
}
No need to import any h3 types for this if you are using nuxt I place this in a types.d.ts at the root of my project
Hendrik Jan
Hendrik JanOP4mo ago
@Gerbuuun Thanks. It seems like I had some other problems with TypeScript to fix first. And probably a restart of the server also fixed something. Now I'm using const context = event.context as Context and it is working. Your solution looks like the way to do it, but I coudn't get it to work in my project. I might try that again later.
Want results from more Discord servers?
Add your server