What is the meaning of viewer field in GraphQL?

Sibelius Seraphini picture Sibelius Seraphini · Jun 4, 2016 · Viewed 8.8k times · Source

What is the purpose of root query field viewer in GraphQL?

Based on this article, viewer could be used to accept a token parameter so we can see who is currently logged in.

How should I implement it?

Answer

Ahmad Ferdous picture Ahmad Ferdous · Jun 5, 2016

Purpose of viewer root query field

viewer is not something GraphQL or Relay-specific. Most web applications serve some purposes of its users or viewers. The top level entity to model the various data served to the user can be named as viewer. You can also name it user. For example, the Relay todo example has a viewer root query field:

viewer: {
  type: GraphQLUser,
  resolve: () => getViewer(),
},

We may also do without viewer. For instance, Relay starwars example does not have any viewer root query field.

In short, having this viewer as a root query field of the GraphQL schema enables us to provide data based on the current user.

Implementation: How to use authentication token together with viewer

My answer follows what is already described in your mentioned article. The steps are:

  1. On the server-side, create a mutation to obtain an authentication token. Let's name it LoginMutation. Input to this mutation are the user credentials and the output is an authentication token.

  2. On the client-side, if you use relay framework, implement a client-side mutation. After the mutation is successful, store the authentication token.

  3. On the client-side Relay code, add authToken parameter for your viewer queries. The value of authToken is the authentication token received after successful login mutation.

An alternative

As already mentioned in the article, an alternative way of authenticating user is to do it outside of GraphQL. You may want to see two excellent answers this and this for details.

Jonas Helfer wrote a two-part article on this, which you'll find very useful: Part 1, Part 2