Apollo server: A better way to authenticate and return user data

Leonardo Correa
2 min readNov 11, 2020

The usual way to write SPA apps with REST is to have one call to authenticate and another call to retrieve the home page data. I am going to show you the unorthodox way to authenticate users and provide a great experience and improve system performance.

Before GraphQL, we used to make an API call to authenticate the user, return the JWT, store it, and make another call to the same server to retrieve the user profile or home page data. Most of the time, you have to request the Membership data twice: once for authentication, second to display the actual data. As a result, users have to wait for authentication, then wait again for the home page to load. This post is a follow up on my techniques to improve the user experience with Apollo. Here is my first post:

The “REST” way to think and the way people will tell you to do is this way:

mutation {
loginUser(input: { memberId: "123456789", password: "mypassword" }) {
access_token expires_in} }}

I came up with a design pattern to authenticate users, and in the same call, return the JWT and user data to immediately display relevant data to users. This pattern doesn’t have a name. I call it “Login with data returned”. Let’s leave the name discussion out and focus on the solution.

Here is the improved version:

mutation {  loginUser(input: {  memberId: "123456789", password: "mypassword" }) {    access_token    expires_in    membership {      id      firstName      lastName    }  }}

Your authentication resolver needs to support the data returned in addition to the JWT. The “membership” field returned could be user profile or just enough to display the data immediately to users. Please refer to the typeDefs: https://codesandbox.io/s/apollo-server-example-8d4bp?file=/type-defs.js:920-971

With this unusual, undocumented, and unorthodox pattern, we were able to decrease almost 50% of calls to Membership. Now we authenticate and return the membership, all in one call to the back-end systems.

Please let me know if you have any suggestions or if you use any other patterns to retrieve the data. You could also suggest a name for this pattern?

Here is the screenshot of the query and the result:

See it in action

--

--

Leonardo Correa

#Brazilian/Australian, #Frontend Dev, #JiuJitsu addicted, #SoccerPlayer, #WorldTraveller, #dad https://bjjnerd.vercel.app