Search code examples
apollo-server

Apollo Server Context Request Property Does Not Exist


Here's my Apollo Server definition.

  const server = new ApolloServer({
    schema,
    context: (async ({ req }) => {
      console.log(req);
      return {};
    }),
    csrfPrevention: true,
    cache: 'bounded',
    plugins: [
      ApolloServerPluginDrainHttpServer({ httpServer }),
      ApolloServerPluginLandingPageLocalDefault({ embed: true }),
    ],
  });

As we can see that auth property does exists in the req object but somehow when I tried to get the value, an error thrown Property 'auth' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' How can I retrieve the auth property?

<ref *2> IncomingMessage {
  ...,
  auth: { sub: '1234567890', name: 'John Doe', iat: 1516239022 },
  body: { query: 'query Query() {\n  }\n}\n' },
  _body: true,
  length: undefined,
  [Symbol(kCapture)]: false,
  [Symbol(RequestTimeout)]: undefined
}


Solution

  • after a little bit try and error, I can solve this issue by cast the context request to express-jwt.Request type as the code shown below,

    const server = new ApolloServer({
      schema,
      context: (({ req }: { req: Request }) => {
        console.log(req.auth);
        return {};
      }),
      csrfPrevention: true,
      cache: 'bounded',
      plugins: [
        ApolloServerPluginDrainHttpServer({ httpServer }),
        ApolloServerPluginLandingPageLocalDefault({ embed: true }),
      ],
    });