Search code examples
graphqlrelayjsrelaygraphql-js

How to authenticate in relay


what is the correct point to authenticate a user ?

going by the relay starter kit as an example.

this would seem like be the point to query (i have added the args id )

var queryType = new GraphQLObjectType({
  name: 'Query',
  fields: () => ({
    node: nodeField,
    // Add your own root fields here
    viewer: {
      args: {
        id: {
          type: GraphQLString
        },
      },
      type: userType,
      resolve: (_, args) => getViewer(args.id),
    },
  }),
});

then in the database do something like

getViewer: (id) => id === viewer.id ? viewer : null,

now its this point where it's falling apart, where would be the place to request the id be made from ? i would assume the route

export default class extends Relay.Route {
  static queries = {
    viewer: () => Relay.QL`
      query {
        viewer(id:"1")
      }
    `,
  };
  static routeName = 'AppHomeRoute';
}

this isn't working.


Solution

  • First you need to drop an auth middleware into your server (http://passportjs.org/ for instance).Then you have to pass the auth information to the graphql middleware (read about how to do it here https://github.com/graphql/express-graphql#advanced-options) and you can finally access that information using the 3rd argument to the resolve(parentValue, args, -->session) function. Here's what the actual auth endpoint could look like https://github.com/igorsvee/react-relay-example/blob/master/server/routes.js#L29-L51