Fullstack accounts for Apollo: server side
Last updated 2 years ago by lorensr .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install apollo-accounts-password-server 
SYNC missed versions from official npm registry.

Apollo Accounts Password—Server npm version

Server side of Apollo Accounts Password, a full-stack JS accounts system for Apollo and MongoDB.


npm install apollo-accounts-password-server

import { ApolloServer, makeExecutableSchema } from 'apollo-server'
import { merge } from 'lodash'
import mongodb from 'mongodb'

import {
} from 'apollo-accounts-password-server'

const start = async () => {
  const client = await mongodb.MongoClient.connect(process.env.MONGO_URL)
  const db = client.db()

  const accounts = createApolloAccounts({
    tokenSecret: process.env.TOKEN_SECRET,
      process.env.NODE_ENV === 'production'
        ? 'https://myapp.com'
        : 'http://localhost:3000'

  const typeDefs = `
  type PrivateType @auth {
    field: String

  type Query {
    publicField: String
    privateField: String @auth
    privateType: PrivateType
    adminField: String @auth

  type Mutation {
    _: String 

  extend type User {
    firstName: String

  const resolvers = {
    Query: {
      publicField: () => 'public',
      privateField: () => 'private',
      privateType: () => ({
        field: () => 'private'
      adminField: (root, args, context) => {
        if (context.user.isAdmin) {
          return 'admin field'
    User: {
      firstName: () => 'first'

  const schema = makeExecutableSchema({
    typeDefs: [typeDefs, accounts.typeDefs],
    resolvers: merge(accounts.resolvers, resolvers),
    schemaDirectives: {

  const server = new ApolloServer({
    context: ({ req }) => accountsContext(req)

  server.listen(4000).then(({ url }) => {
    console.log(`????  Server ready at ${url}`)


createApolloAccounts() generates typedefs, resolvers, and directives for us to use in our schema. It creates a User type that we can extend and an @auth directive for fields and types that returns an error if the client is not logged in. It also creates resolvers and types used by apollo-accounts-password-client.


See flyblackbird/apollo-accounts




options format. Detailed format:

  • options.db: (Required) the database connection. Using the mongodb module:
const client = await mongodb.MongoClient.connect(process.env.MONGO_URL)

// uses the db listed at the end of the MONGO_URL
const db = client.db() 
// or:
const db = client.db('my-db-name')

Using Mongoose:

await mongoose.connect(
  { useNewUrlParser: true }
const db = mongoose.connection
  • options.tokenSecret: (Required) a secret the library uses for token creation. You can generate a secret with openssl rand -base64 30.
  • options.siteUrl: (Required) eg 'http://localhost:3000' or 'https://myapp.com'
  • options.sendMail: (Required) a function that sends an email. For instance:
import nodemailer from 'nodemailer'
let transporter = nodemailer.createTransport('smtps://username:password@smtp.example.com/?pool=true')

sendMail: ({ from, subject, to, text, html }) => {
  }, (err, info) => {
  • options.emailTemplates: templates for auth emails. Format. Defaults:
  from: 'accounts-js <no-reply@accounts-js.com>',
  verifyEmail: {
    subject: () => 'Verify your account email',
    text: (user, url) =>
      `To verify your account email please click on this link: ${url}`,
    html: (user, url) =>
      `To verify your account email please <a href="${url}">click here</a>.`,
  resetPassword: {
    subject: () => 'Reset your password',
    text: (user, url) => `To reset your password please click on this link: ${url}`,
    html: (user, url) => `To reset your password please <a href="${url}">click here</a>.`,
  • options.userObjectSanitizer: a function that, given a user object from the database, returns a filtered user object that will be sent to the client. The default only removes authentication data (user.services). Here is an example that removes the username field:
userObjectSanitizer: (user, omit, pick) => omit(user, ['username'])
  • options.tokenConfigs: expiration for the access and refresh tokens. The default values are:
tokenConfigs: {
  accessToken: {
    expiresIn: '90m',
  refreshToken: {
    expiresIn: '90d',

The refresh token expiration matches Meteor's default 90-day login token expiration.

Expiration format matches jwt.sign's options.expiresIn.

  • options.impersonationAuthorize: a function that, given the current user and the target of impersonation, returns whether to allow impersonation. For example:
impersonationAuthorize: (currentUser, targetUser) => currentUser.isAdmin


Sets the request context so that we can access context.user in our resolvers:

const server = new ApolloServer({
  context: ({ req }) => accountsContext(req)



cb is called each time a user successfully logs in via login(). It's given an object with information about the request, including a user property.

cb is not called when an access token is refreshed.



cb is called after a user is successfully created (by a call to createUser()). It's given the user record that was saved in the database.


This package is like Apollo Boost—if at some point you need more configuration options than this package exposes, you can eject by directly installing the below accounts-js packages and configuring them yourself:

npm install @accounts/server @accounts/password @accounts/graphql-api @accounts/database-manager @accounts/mongo

See index.js


Current Tags

  • 0.3.0-beta.26-1                                ...           latest (2 years ago)

2 Versions

  • 0.3.0-beta.26-1                                ...           2 years ago
  • 0.3.0-beta.26                                ...           2 years ago
Maintainers (1)
Today 0
This Week 0
This Month 2
Last Day 0
Last Week 0
Last Month 3
Dependencies (8)
Dev Dependencies (3)
Dependents (0)

Copyright 2014 - 2017 © taobao.org |