Implementing GraphQL authentication and mutations
We are now going to implement a way to create new posts using GraphQL. To define fields that change the database state, we need to create them under the mutation type. Before we can do that, however, we first need to implement authentication in GraphQL, so that we can access the currently logged-in user when creating a post.
Adding authentication to GraphQL
Because we are using GraphQL with Express, we can use any Express middleware with GraphQL and pass it to our resolvers as context. As such, we can use the existing express-jwt middleware to parse the JWT. Let’s get started adding authentication to GraphQL now:
- Our current configuration of the
requireAuthmiddleware ensures that the user is logged in and throws an error if they are not. However, this is an issue when passing theauthcontext to GraphQL, because not all queries require authentication. We are now going to create a newoptionalAuthmiddleware that...