Authentication patterns in GraphQL

From the GraphQL cheat sheet ยท Authentication & Authorization ยท verified Jul 2026

Authentication patterns

javascript
// Authentication setup
const jwt = require('jsonwebtoken');
const { GraphQLError } = require('graphql');

// Context with authentication
const server = new ApolloServer({ typeDefs, resolvers });

// Context moves to the integration function (Apollo Server 4+)
app.use('/graphql', cors(), express.json(), expressMiddleware(server, {
  context: async ({ req }) => {
    // Get token from header
    const token = req.headers.authorization?.replace('Bearer ', '');
    
    let user = null;
    if (token) {
      try {
        // Verify token
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        
        // Get user from database
        user = await db.user.findUnique({
          where: { id: decoded.userId }
        });
      } catch (err) {
        // Invalid token, but don't throw here
        console.error('Invalid token:', err);
      }
    }
    
    return { user, db };
  },
}));

// Login mutation
const resolvers = {
  Mutation: {
    login: async (parent, { email, password }, { db }) => {
      // Find user
      const user = await db.user.findUnique({ where: { email } });
      
      if (!user) {
        throw new GraphQLError('Invalid credentials', { extensions: { code: 'UNAUTHENTICATED' } });
      }
      
      // Check password
      const validPassword = await bcrypt.compare(password, user.password);
      
      if (!validPassword) {
        throw new GraphQLError('Invalid credentials', { extensions: { code: 'UNAUTHENTICATED' } });
      }
      
      // Generate token
      const token = jwt.sign(
        { userId: user.id, email: user.email },
        process.env.JWT_SECRET,
        { expiresIn: '7d' }
      );
      
      return {
        token,
        user
      };
    },
    
    register: async (parent, { input }, { db }) => {
      // Check if user exists
      const existing = await db.user.findUnique({
        where: { email: input.email }
      });
      
      if (existing) {
        throw new Error('User already exists');
      }
      
      // Hash password
      const hashedPassword = await bcrypt.hash(input.password, 10);
      
      // Create user
      const user = await db.user.create({
        data: {
          ...input,
          password: hashedPassword
        }
      });
      
      // Generate token
      const token = jwt.sign(
        { userId: user.id },
        process.env.JWT_SECRET
      );
      
      return { token, user };
    }
  }
};
๐Ÿ’ก Use context for auth state
โšก JWT tokens common for GraphQL
๐Ÿ“Œ Check auth in resolvers or middleware
๐Ÿ” Never expose sensitive fields
Back to the full GraphQL cheat sheet