Skip to content
Strategy and utilities to use passport.js with GraphQL server
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.
babel.config.js Fixed babel config May 25, 2019

graphql-passport provides simple functionality to authenticate with Passport.js from mutation resolvers.

Inside your resolvers you can get access to the following functions and attributes inside the context.

context.authenticate('graphql-local', { email, password })

authenticate and login are basically passport.authenticate and passport.login wrapped in a promise. user, logout, isAuthenticated and isUnauthenticated are just copies of the corresponding passport functions and attributes.


For a full working example including detailed instructions visit this blog post about how to authenticate with user credentials using GraphQL and passport. Continue reading here for a short summary.

Initialize the GraphQLLocalStrategy and create the GraphQL context by using buildContext.

import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import passport from 'passport';
import { GraphQLLocalStrategy, buildContext } from 'graphql-passport';

  new GraphQLLocalStrategy((email, password, done) => {
    // Adjust this callback to your needs
    const users = User.getUsers();
    const matchingUser = users.find(user => email === && password === user.password);
    const error = matchingUser ? null : new Error('no matching user');
    done(error, matchingUser);

const app = express();

const server = new ApolloServer({
  context: ({ req, res }) => buildContext({ req, res, User }),

server.applyMiddleware({ app, cors: false });

app.listen({ port: PORT }, () => {
  console.log(`🚀 Server ready at http://localhost:${PORT}${server.graphqlPath}`);

Inside your resolvers you can call context.authenticate to authenticate the user with the given credentials. If you want to use expression-session as well you need to call context.login(user) after authenticate.

const resolvers = {
  Query: {
    currentUser: (parent, args, context) => context.user,
  Mutation: {
    login: async (parent, { email, password }, context) => {
      // instead of email you can pass username as well
      const { user } = await context.authenticate('graphql-local', { email, password });

      // call login if you want to use express-session
      // context.login(user);

      return { user }
You can’t perform that action at this time.