Firebase Authentication with GraphQL and React Client [JavaScript]


In this article, I would like to share GraphQL of server side and React of client side with Firebase auth.

🏈 Client Side

Installation

Install:

yarn add apollo-boost firebase

Code

After logging into Firebase Authentication in client side, you can get a token of firebase.
So, please send the token information to your GraphQL server.

import ApolloClient, { InMemoryCache } from "apollo-boost";

const token = await auth.currentUser.getIdToken(true);

const client = new ApolloClient({
cache: new InMemoryCache(),
headers: { token: token },
uri: "http://localhost:3000/graphql"
});

More detail is Verify ID Tokens.

🐮 GraphQL

Installation

yarn add apollo-resolvers firebase-admin

Code

Please get the following secret information by the following URL:

Before verifying the token, you need to initialize App.

// Firebase
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert({
projectId: FIREBASE_PROJECT_ID,
clientEmail: FIREBASE_CLIENT_EMAIL,
privateKey: FIREBASE_PRIVATE_KEY
}),
databaseURL: FIREBASE_DATABASE_URL
});

After then, please set the token of headers to GraphQL context.

graphqlExpress((req, res) => {
const context = createExpressContext(
{
firebaseToken: req.headers.token
},
res
);

return {
schema,
context
};
})

Now, your GraphQL server can confirm the token in resolvers.

const validateAuthorization = async (token: string) => {
await firebaseAdmin.auth().verifyIdToken(token);
};

😎 References

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!