I'm new to Apollo and relatively new to TypeScript, so maybe I'm missing something. I'm trying to get my types straight in my ApolloServer constructor. The documentation for the constructor says that the context parameter takes an untyped object with a single key req, like so:
context: ({ req }) => ({
authScope: getScope(req.headers.authorization)
}),
However, in types.d.ts, context is defined as taking context?: Context<any> | ContextFunction<any>;, where ContextFunction is:
export declare type ContextFunction<T = any> = (context: Context<T>) => Promise<Context<T>>;
This typing is claiming that the context creating function _takes a context_, not just returns one. Since req is not typed to be a member of context, TypeScript says I'm doing something wrong.
Also, from reading the documentation, it really sounds like the return type should be Context<T> | Promise<Context<T>>; it doesn't HAVE to be an async function, does it?
If my take on this issue is correct, could you please make a proper type for the callback function's first parameter, and update the typings? And also, if you could mention this type in the documentation, and also document that req is an http.IncomingMessage, I'd be very grateful! (as a newcomer to Node, I've noticed that a lot of node documentation makes assumptions such as knowing that incoming requests in any node library is usually a leaked type from the node standard library).
Something like:
interface RequestContext { req: IncomingMessage }
declare type ContextFunction<T> = (requestContext: RequestContext) => Context<T> | Promise<Context<T>>;
Thanks!
A solution for me was, create a type:
type Req = { req: IncomingMessage }
const server = new ApolloServer({
schema,
context: async({req}: Req) => {
const authorization = req.headers.authorization
or you can use
const server = new ApolloServer({
schema,
context: async(incomingContext: { req: IncomingMessage } => {
const authorization = incomingContext.req.headers.authorization
and you can use this, but type of req is not a Request
context: async(contextExpress: {req: express.Request }) => {
console.log(contextExpress.req instanceof IncomingMessage) // print true
PRs for this seem to have been merged, should the fix be published and the issue closed?
Yep, this should have been closed a while ago.
Most helpful comment
A solution for me was, create a type:
or you can use
and you can use this, but type of req is not a Request