DEV Community

Cover image for GraphiQL with Firebase Auth
Konstantin Tarkus
Konstantin Tarkus

Posted on

GraphiQL with Firebase Auth

If you're using GraphiQL IDE provided by Helix GraphQL server, you may find that it's not that trivial to hook it up with Firebase (Google Identity Platform) auth flow.

One way to make it work, is to inject the following code snippet into the HTML page containing GraphiQL IDE:

<script type="module">
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.0/firebase-app.js";
  import { getAuth } from "https://www.gstatic.com/firebasejs/9.22.0/firebase-auth.js";

  const app = initializeApp({
    projectId: "example",
    appId: "xxxxx",
    apiKey: "xxxxx",
    authDomain: "example.com"
  });

  function setAuthHeader(token) {
    const editor = document.querySelectorAll('.variable-editor .CodeMirror')[1].CodeMirror;
    const headers = JSON.parse(editor.getValue());
    headers.Authorization = token ? "Bearer " + token : undefined;
    editor.setValue(JSON.stringify(headers, null, 2));
  }

  getAuth(app).onIdTokenChanged((user) => {
    if (user) {
      user.getIdToken().then(token => setAuthHeader(token));
    } else {
      setAuthHeader(null);
    }
  });
</script>
Enter fullscreen mode Exit fullscreen mode

Find the full example at https://github.com/kriasoft/relay-starter-kit

Top comments (0)