1

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.

Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64

2 Answers2

3

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),
    }),
  }),
);

Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64
0

Apollo Server v4 introduces a new way of passing data with context such that unlike how we were passing context into the ApolloServer constructor, it is now being passed in the web integration function like below: Find more in the link https://www.apollographql.com/docs/apollo-server/migration/#context-initialization-function

const { url } = await startStandaloneServer(server, {
  context: async ({ req, res }) => ({
    //your data 
});
  listen: { port: 4000 },
});`
Judefabi
  • 29
  • 3