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?
graphqlrelayjs
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?
Best Answer
Purpose of
viewer
root query fieldviewer
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 asviewer
. You can also name ituser
. For example, the Relay todo example has aviewer
root query field:We may also do without
viewer
. For instance, Relay starwars example does not have anyviewer
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:
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.On the client-side, if you use relay framework, implement a client-side mutation. After the mutation is successful, store the authentication token.
On the client-side Relay code, add
authToken
parameter for yourviewer
queries. The value ofauthToken
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