How to add user to the context object in apollo server?

Viewed 791

When I used REST api I used to place users on req.user but now I am doing my first graphql auth and i struggle to place the user on context object.

Here is what I am trying to accomplish but does not work:

  1. get admin ID from token and fetch admin from DB
  2. add fetched admin to the context object so that I can check admin permissions before each resolver
export const validateAccessToken = async (req) => {
  try {
    const accessToken = req.headers.authorization.slice(7);
    if (!accessToken) throw new AuthenticationError('Unauthorized access');

    const { id } = verify(accessToken, process.env.JWT_ACCESS_SECRET);

    const admin = await Admin.findById(id);

    return admin;
  } catch {
    return null;
  }
};
// index.js
import { validateAccessToken } from './auth';

const server = new ApolloServer({
    modules: [auth],
    context: ({ req, res }) => ({ req, res, admin: validateAccessToken(req) }),
  });

The value of admin in context is Promise { <pending> }

1 Answers

The context function can return a promise itself. You can either make the function async or use the chaining API:

import { validateAccessToken } from './auth';

const server = new ApolloServer({
  modules: [auth],
  context: async ({ req, res }) => ({ req, res, admin: await validateAccessToken(req) }),
});


const server = new ApolloServer({
  modules: [auth],
  context: ({ req, res }) =>
    validateAccessToken(req).then(admin => ({ req, res, admin })),
});

Now admin should be part of the context and no longer be a pending promise.

Related