Search code examples
expressgraphqlapolloapollo-server

How to pass context value in apollo-server 4?


In apollo-server 3, I was able to set the context when creating the apollo server like this:

const server = new ApolloServer({
    debug: true,
    schema: executableSchema,
    context: contextFunction(secretValues),
...

My contextFunction looked like this:

export const contextFunction =
  (secretValues: AwsSecretValues) =>
  async ({ req, res }: ExpressContext) => {
    const sessionId = extractSessionIdFromCookies(req.headers.cookie);
    const session = await validateSession(
      sessionId || req.headers.authorization,
    );

    if (session) {
      session.set({ expiresAt: Date.now() + DEFAULT_SESSION_EXTEND_TIME });
      await session.save();

      generateCookie(session._id, res);
    }

    return {
      pubsub,
      dataLoaders: dataLoaderFactory(),
      session,
      req,
      res,
      secretValues,
    };
  };

It was useful, because I didn't have to refresh the session independently at every single resolver, and each resolver had an up-to-date version of it, also I was able to pass in a bunch of other useful stuff.

As I see there's no option for this in apollo-server 4. But what's the whole point of a context if you can't set it (except drilling down stuff to child resolvers)? There must be a way, but cannot find how.


Solution

  • As stated in the docs, the new way of defining the same is:

    app.use(
      // A named context function is required if you are not
      // using ApolloServer<BaseContext>
      expressMiddleware(server, {
        context: async ({ req, res }) => ({
          token: await getTokenForRequest(req),
        }),
      }),
    );