Anyone to show me how to correctly setup `express-...
# orm-help
b
Anyone to show me how to correctly setup
express-jwt
with
Express Apollo Server
? I can't figure out why jwt verification errors are not being thrown back to Apollo. I see
express-jwt
logging the error but never received in Apollo Studio Explorer. I am using it like this but I can't figure out how to blend it into the Apollo/GraphQL error handling loop. Should I apply it as schema middleware or just as a regular express request middleware?:
Copy code
export function createContext(
  req: JWTRequest,
  prismaClient: PrismaClient
): GraphQLContext {
  return {
    req,
    prisma: prismaClient,
  };
}

async function startApolloServer(
  gqlSchema: GraphQLSchema,
  prismaClient: PrismaClient
) {
  dotenv.config();

  const app = express();
   // here is how I am using it but when token is invalid it prevents request from proceeding(which is okay) but the errors are not sent back to Apollo Studio Explorer like any other errors raised by resolvers.
  app.use(
    expressjwt({
      secret: process.env.JWT_SECRET!,
      algorithms: ["HS256"],
      credentialsRequired: false,
    })
  );

  // 1. Http Server
  const httpServer = http.createServer(app);

  // 2. Websocket Server
  const wsServer = new WebSocketServer({
    server: httpServer,
    path: "/",
  });

  const wsServerCleanup = useServer({ schema: gqlSchema }, wsServer);

  // 3. Apollo Server
  const server = new ApolloServer({
    schema,
    context: ({ req }) => {
      return createContext(req, prismaClient);
    },
    csrfPrevention: true,
    plugins: [
      // Proper shutdown for the HTTP server.
      ApolloServerPluginDrainHttpServer({ httpServer }),

      // Proper shutdown for the websocket server
      {
        async serverWillStart() {
          return {
            async drainServer() {
              await wsServerCleanup.dispose();
            },
          };
        },
      },
    ],
  });

  await server.start();
  server.applyMiddleware({
    app,
  });

  await new Promise<any>((resolve: any) =>
    httpServer.listen({ port: process.env.PORT }, resolve)
  );
  console.log(`🚀 Server ready at <http://localhost:4000>${server.graphqlPath}`);
}
✅ 1
Ayt, I just added an error handler that simply ignores the errors from
express-jwt
and calls next middleware on the stack since I am throwing all auth errors via
graphql-shield
and
express-jwt
is just helping me verify and add decoded token as `req.auth`:
Copy code
app.use(function (_err: any, _req: any, _res: any, next: any) {
    next();
  });