Use graphql-express to deal with authorization

peterlitszo

peterlits zo

Posted on March 7, 2022

Use graphql-express to deal with authorization

Why

In this post, I am using apollo client to send GraphQL request in the front-end.

It time to deal with those request and return a response in the back-end.

To do it, we choose express (a JavaScript web framework) as a server.

What's the question?

Well. To deal with the GraphQL request, the best idea is using express-graphql. But it does not have the interface to set cookie to get the authorization.

// init a express server
const GraphQLServer = express();

// deal with the GraphQL request with graphqlHTTP,
// which is from the express-graphql. 
GraphQLServer.use(
  "/graphql",
  graphqlHTTP({
    schema: GraphQLSchema,
    graphiql: GRAPHIQL,
  })
);

// Listen to port 4000.
GraphQLServer.listen(4000, () => {
  console.log("Listening on localhost:4000...");
});
Enter fullscreen mode Exit fullscreen mode

Now we do not have idea.

Solution

The solution is that send the req and res into the graphqlHTTP's context:

GraphQLServer.use(
  "/graphql",
  // The returned value of graphqlHTTP is also a function.
  // We just add a wrapper to set its context.
  (req, res) => {
    return graphqlHTTP({
      schema: GraphQLSchema,
      graphiql: GRAPHIQL,
      context: { req, res },
    })(req, res)
  })
);
Enter fullscreen mode Exit fullscreen mode

Click for more information: https://stackoverflow.com/questions/46023367/graphql-issuing-jwt-cookie

đź’– đź’Ş đź™… đźš©
peterlitszo
peterlits zo

Posted on March 7, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related