# graphql-passport

> Strategy and utilities to use passport.js with GraphQL server

Latest version **0.6.11** (published 2026-10-15) · MIT license · 0 weekly downloads

## Install

```sh
npm install graphql-passport
pnpm add graphql-passport
yarn add graphql-passport
bun add graphql-passport
```

## Health

**Score 65/100 (B)** — status: active.

Positive: has types; no vulnerabilities; recently updated; high maintenance score; high quality score.

Warnings: low downloads; no esm support; large bundle; pre 1.0.

## Facts

| | |
|---|---|
| Version | 0.6.11 |
| Published | 2026-10-15 |
| First published | 2019-05-24 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 18.8 MB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Maintainers | jkettmann, ericbf |
| Keywords | graphql, passport, authorization, authentication |

## Links

- npm: https://www.npmjs.com/package/graphql-passport
- Repository: https://github.com/ericmakesapps/graphql-passport
- Homepage: https://github.com/ericmakesapps/graphql-passport#readme
- Issues: https://github.com/ericmakesapps/graphql-passport/issues
- npm.io page: https://npm.io/package/graphql-passport

## Dependencies (1)

- [passport-strategy](https://npm.io/package/passport-strategy.md) ^1.0.0

## Recent versions

- 0.6.11 (latest) — 2026-10-15
- 0.6.10 — 2026-10-15
- 0.6.9 — 2026-10-15
- 0.6.8 — 2024-01-19
- 0.6.7 — 2023-07-18
- 0.6.6 — 2023-07-09
- 0.6.5 — 2022-12-02
- 0.6.4 — 2021-09-24
- 0.6.3 — 2020-03-15
- 0.6.2 — 2020-03-15
- 0.6.1 — 2020-02-10
- 0.6.0 — 2020-01-29
- 0.5.0 — 2019-10-23
- 0.4.1 — 2019-10-17
- 0.4.0 — 2019-10-15
- … 9 more at https://npm.io/package/graphql-passport/versions

## README

`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.

```js
context.authenticate("graphql-local", { email, password }) // not available for subscriptions
context.login(user) // not available for subscriptions
context.logout() // not available for subscriptions
context.isAuthenticated()
context.isUnauthenticated()
context.getUser()
```

`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.

## Usage

For a full working example including detailed instructions visit this blog post about [how to authenticate with user credentials using GraphQL and passport](https://jkettmann.com/authentication-and-authorization-with-graphql-and-passport). Continue reading here for a short summary.

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

```js
import { ApolloServer } from "apollo-server-express"
import express from "express"
import session from "express-session"
import { buildContext, GraphQLLocalStrategy } from "graphql-passport"
import passport from "passport"

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

const app = express()
app.use(session(options)) // optional
app.use(passport.initialize())
app.use(passport.session()) // if session is used

const server = new ApolloServer({
	typeDefs,
	resolvers,
	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}`)
})
```

If you need to pass the `request` object into `GraphQLLocalStrategy`, you can pass the `passReqToCallback` option in an object as the first argument, then add it as the first argument of the verify function:

```js
passport.use(
  new GraphQLLocalStrategy( { passReqToCallback: true }, (req, email, password, done) => {
    // access the request object
    const host = req.headers.host;
    ...
  })
);
```

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

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

			// only required if express-session is used
			context.login(user)

			return { user }
		}
	}
}
```

## Usage with subscriptions

When using subscriptions you may want to only expose events related to the currently logged in user. Since subscriptions use websockets they don't pass the session and Passport middlewares like queries or mutations. To be able to access the user object from the context inside the subscription resolvers you need to do some additional work.

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

...
const sessionMiddleware = session(options); // optional
const passportMiddleware = passport.initialize();
const passportSessionMiddleware = passport.session(); // if session is used

const app = express();
app.use(sessionMiddleware);
app.use(passportMiddleware);
app.use(passportSessionMiddleware);

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req, res }) => buildContext({ req, res, User }),
  subscriptions: {
    onConnect: createOnConnect([
      sessionMiddleware,
      passportMiddleware,
      passportSessionMiddleware,
    ])
  }
});

...
```

Now you can access `isAuthenticated()`, `isUnauthenticated()`, and `getUser()` on the context. Follwing example only allows a connection when the user is logged in. It only notifies the user if they are the receiver of the message.

```js
const resolvers = {
  Subscription: {
    messageReceived: {
      subscribe: withFilter(
        (parent, args, context) => {
          if (context.isUnauthenticated()) {
            throw new Error('You need to be logged in');
          }
          return pubSub.asyncIterator([MESSAGE_RECEIVED])
        },
        (payload, variables, context) => payload.messageReceived.receiverId === context.user.id,
      ),
    },
  },
  Query: { ... },
  Mutation: {
    ...
    sendMessage: (parent, { text, receiverId }, context) => {
      const message = { text, receiverId };
      pubSub.publish(MESSAGE_RECEIVED, { messageReceived: message });
      return message;
    }
  },
};
```

## Typescript

This library cannot know what fields the user type contains in a given project. In order to define your own `Context` type you must provide your user type to the `PassportContext`/`PassportSubscriptionContext` generic parameter.

### Creating a simple context

First, we need to define the user type. In this example the type is defined in a file called `MyUser.ts` and has the fields `firstName` and `lastName`.

```ts
export type MyUser = {
	firstName: string
	lastName: string
}
```

We can now define the context interface specific to the project. We use the above user type in place of the generic for the `PassportContext` and `PassportSubscriptionContext` interfaces. For this example we create a file named `MyContext.ts` with following content.

```ts
import { Request as ExpressRequest } from 'express';
import { PassportSubscriptionContext, PassportContext } from 'graphql-passport';
import { MyUser } = './path/to/MyUser';

export interface MyContext extends PassportContext<MyUser, ExpressRequest>{}

export interface ProjectSubscriptionContext extends PassportSubscriptionContext<MyUser, ExpressRequest>{}
```

### Using the context type in the resolvers

The `MyContext` type can now be used inside the resolvers. Below you can see an example of a resolver that concatenates the user's first and last name defined above.

```ts
import { MyContext } from "./path/to/MyContext"

const resolvers = {
	Query: {
		User: {
			name: (parent: unknown, data: SomeData, context: MyContext) => {
				const user = context.getUser()
				return `${user.firstName} ${user.lastName}`
			}
		}
	}
}
```

### Working with data sources

If you use [Apollo's data sources](https://www.apollographql.com/docs/apollo-server/data/data-sources/) you might want to add `dataSources` to the interface. This can be achieved as follows.

```ts
import { Request as ExpressRequest } from 'express';
import { PassportSubscriptionContext, PassportContext } from 'graphql-passport';
import { MyUser } = './path/to/MyUser';

export interface MyContext extends PassportContext<MyUser, ExpressRequest>{
  dataSources: {
    myOtherAPI: { ... }
  }
}

export interface ProjectSubscriptionContext extends PassportSubscriptionContext<MyUser, ExpressRequest>{
  dataSources: {
    myOtherAPI: { ... }
  }
}
```

---
_Source: https://npm.io/package/graphql-passport · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
