React GraphQL & ApolloServer: Unhandled Rejection (Error): GraphQL error: Cannot access 'post' before initialization

I have a simple social media app that uses: GraphQL & ApolloServer as a backend where users can like posts. But an error occurs when a user who isn’t logged in tries to like a button and an error called:

Unhandled Rejection (Error): GraphQL error: Authorization header must be provided

occurs.

This is the code for the likePost mutation…

    async likePost(_, { postId }, context) {
  const { username } = checkAuth(context);

  const post = await Post.findById(postId);
  if (post) {
    if (post.likes.find((like) => like.username === username)) {

      post.likes = post.likes.filter((like) => like.username !== username);
    } else {
      post.likes.push({
        username,
        createdAt: new Date().toISOString()
      });
    }

    await post.save();
    return post;
  } else throw new UserInputError('Post not found');
}

},

This is the code for checking authorization file.

   const { AuthenticationError } = require('apollo-server');

const jwt = require('jsonwebtoken');
const { SECRET_KEY } = require('../config');

module.exports = (context) => {
  // context = { ... headers }
  const authHeader = context.req.headers.authorization;
  if (authHeader) {
    // Bearer ....
    const token = authHeader.split('Bearer ')[1];
    if (token) {
      try {
        const user = jwt.verify(token, SECRET_KEY);
        return user;
      } catch (err) {
        throw new AuthenticationError('Invalid/Expired token');
      }
    }
    throw new Error("Authentication token must be 'Bearer [token]");
  }

throw new Error(‘Authorization header must be provided’);
};

How do I go about solving this problem so that no error comes up when an unregistered user tries to like a post?

26 thoughts on “React GraphQL & ApolloServer: Unhandled Rejection (Error): GraphQL error: Cannot access 'post' before initialization”

Leave a Comment