Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 87 ยท Data Fetching

Vue with Firebase, Supabase and GraphQL

Connect Vue 3 to backend services: auth and database calls from a composable with Firebase and Supabase, real-time subscriptions with cleanup, and GraphQL queries with Apollo or urql.

You do not always need to write your own server. Backend-as-a-service (BaaS) products such as Firebase (Google) and Supabase (built on PostgreSQL) give your Vue app sign-in, a database and live updates through a JavaScript library. GraphQL is a different idea: a query language that lets the page ask for exactly the fields it needs from one endpoint, usually through Apollo or urql.

All of them plug into Vue the same way, and that way is the point of this lesson: keep the service behind a small module or composable, so components work with refs and plain functions and never touch the vendor library directly. Then the vendor can change and your components do not.

The libraries cannot be installed on this site, so the vendor code below is read-only. The runnable examples use stand-ins that imitate the shape of the APIs with timers and an in-memory table. They are not the real products.

The pattern: client module, composable, component

Every service follows three layers:

flowchart LR
    C["Component<br/>refs + buttons"] --> U["Composable<br/>useTodos, useAuth"]
    U --> S["Service client<br/>one module, one config"]
    S --> B["Backend<br/>Firebase / Supabase / GraphQL"]

Components know refs; composables know the vendor's functions; one module holds the keys and the client.

Firebase

Firebase's modern (v9+) SDK is modular, so bundlers include only what you import. The web config values (API key, project id) are identifiers, not secrets: your security comes from Firebase security rules on the server, not from hiding the config.

JavaScript
// src/firebase.js
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";

const app = initializeApp({
  apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
  authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
  projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
});

export const auth = getAuth(app);
export const db = getFirestore(app);

A composable for the signed-in user and for a live list:

JavaScript
// src/composables/useAuth.js
import { ref, onScopeDispose } from "vue";
import { onAuthStateChanged, signInWithEmailAndPassword, signOut } from "firebase/auth";
import { auth } from "../firebase";

export function useAuth() {
  const user = ref(null);
  const ready = ref(false);

  const unsubscribe = onAuthStateChanged(auth, (current) => {
    user.value = current;
    ready.value = true;          // we now know if someone is signed in
  });
  onScopeDispose(unsubscribe);

  return {
    user,
    ready,
    login: (email, password) => signInWithEmailAndPassword(auth, email, password),
    logout: () => signOut(auth),
  };
}
JavaScript
// src/composables/useTodos.js
import { ref, onScopeDispose } from "vue";
import { collection, query, orderBy, onSnapshot, addDoc } from "firebase/firestore";
import { db } from "../firebase";

export function useTodos() {
  const todos = ref([]);
  const error = ref(null);

  const q = query(collection(db, "todos"), orderBy("createdAt"));
  const unsubscribe = onSnapshot(
    q,
    (snapshot) => {
      todos.value = snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
    },
    (e) => { error.value = e.message; },
  );
  onScopeDispose(unsubscribe);   // stop listening when the component goes away

  const add = (title) => addDoc(collection(db, "todos"), { title, done: false, createdAt: Date.now() });
  return { todos, error, add };
}

onSnapshot is real-time by design: it calls your callback with the current data and again on every change, and it returns an unsubscribe function. Forgetting to call it is the most common leak with Firebase, and the same applies to every subscription in this lesson.

Supabase

Supabase exposes a PostgreSQL database through a JavaScript client. The public anon key is also meant to be in the browser; Row Level Security (RLS) policies in the database decide who can read or write each row. A table without RLS policies that is reachable with the anon key is open to everyone, so enable RLS and write policies before you ship.

JavaScript
// src/supabase.js
import { createClient } from "@supabase/supabase-js";

export const supabase = createClient(
  import.meta.env.VITE_SUPABASE_URL,
  import.meta.env.VITE_SUPABASE_ANON_KEY,
);
JavaScript
// src/composables/useTodos.js (Supabase version)
import { ref, onMounted, onScopeDispose } from "vue";
import { supabase } from "../supabase";

export function useTodos() {
  const todos = ref([]);
  const error = ref(null);

  async function load() {
    const { data, error: e } = await supabase.from("todos").select("*").order("id");
    if (e) { error.value = e.message; return; }   // the client returns errors, it does not throw
    todos.value = data;
  }

  async function add(title) {
    const { error: e } = await supabase.from("todos").insert({ title });
    if (e) error.value = e.message;
  }

  // Live updates through Postgres changes
  const channel = supabase
    .channel("todos-feed")
    .on("postgres_changes", { event: "*", schema: "public", table: "todos" }, load)
    .subscribe();

  onMounted(load);
  onScopeDispose(() => supabase.removeChannel(channel));

  return { todos, error, add };
}

Authentication looks like await supabase.auth.signInWithPassword({ email, password }) to sign in and supabase.auth.onAuthStateChange((event, session) => { ... }) to follow the session; the latter also returns something you must unsubscribe from (data.subscription.unsubscribe()).

Notice that Supabase calls return { data, error } instead of throwing, while Firebase functions return promises that reject. A composable is the right place to normalize that difference into your own error ref.

Stand-in: a backend with auth, a table and live updates

The next example builds a miniature of this pattern: a fake client with auth.signIn, a todos table with select/insert, and a subscribe function that returns an unsubscribe, exactly the kind of API Firebase and Supabase expose. The composables are written as you would write them for the real services.

Auth and a live table through composables (stand-in backend)

Try adding a todo while signed out: the "row-level security" error appears in the page and the list does not change. Sign in with the password secret and add again: the insert succeeds, the table notifies its subscriber, and the list reloads. The components contain no vendor calls at all, and the guards that matter (who may write) live in the backend, as they must.

GraphQL

With GraphQL the browser sends one request to one URL (often /graphql) containing a query that lists the fields it wants, plus variables. The reply has the same shape as the query:

GRAPHQL
query UserWithPosts($id: ID!) {
  user(id: $id) {
    name
    posts(first: 3) { title }
  }
}

The response is JSON with a data object and, if something went wrong, an errors array. Note that GraphQL usually answers HTTP 200 even for errors, so checking response.ok is not enough: look at errors.

Two libraries cover most Vue projects. Apollo (@vue/apollo-composable) has a normalized cache and many features. urql (@urql/vue) is smaller and simpler.

JavaScript
// Apollo
import { useQuery } from "@vue/apollo-composable";
import gql from "graphql-tag";

const { result, loading, error } = useQuery(gql`
  query User($id: ID!) { user(id: $id) { name } }
`, { id: userId });                       // variables may be a ref or a getter: it refetches when they change

// urql
import { useQuery } from "@urql/vue";
const { data, fetching, error } = useQuery({ query: USER_QUERY, variables: { id: userId } });

Both return refs (loading or fetching, error, and the data), so the template looks just like the fetching pattern from Fetching Data. The next example shows what is happening underneath, with a fake endpoint: a POST of { query, variables }, a data and errors envelope, and a tiny useQuery.

A minimal GraphQL client and useQuery (fake endpoint)

User 99 does not exist: the fake server still answers with status 200 but puts a message in errors, and the client turns that into an exception, so the page shows one clear error state. Real libraries do this check for you and also give you partial data plus errors when only one field failed.

Choosing

Need Good fit
Prototype fast, real-time, no server Firebase or Supabase
Relational data, SQL, open source, self-hosting option Supabase
Mobile apps and web together, push notifications Firebase
One page needs data from many resources, typed schema GraphQL
A server you already run with a REST API Plain fetch or Axios (data fetching)

Whatever you choose: authorize on the server (security rules, RLS, resolvers), never in the page; put keys in environment variables (Vite env variables); unsubscribe in onScopeDispose; and keep every vendor call behind a composable.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A Firebase onSnapshot listener is started in a composable. What must you do when the component unmounts?

    Listeners keep running until unsubscribed. Without cleanup you leak connections and update refs of components that are gone.
  2. 2. What does a Supabase query such as supabase.from('todos').select() return when it fails?

    The Supabase client returns { data, error } instead of throwing, so you must check error yourself.
  3. 3. Why can the public Firebase config or Supabase anon key sit in browser code?

    Everything in the browser is visible to users. Safety comes from rules enforced on the server, not from secrecy of the client key.
  4. 4. A GraphQL server answers HTTP 200 with { "data": null, "errors": [...] }. What should your client do?

    GraphQL reports many failures inside the response body, so response.ok alone is not enough.

Summary

  • Put the backend client in one module and wrap it in composables that expose refs and actions.
  • Firebase and Supabase give auth, a database and live updates; secure them with server-side rules, because client keys are public.
  • Every subscription (onSnapshot, Supabase channels, auth listeners) returns a way to stop it; call it in onScopeDispose.
  • Firebase rejects promises; Supabase returns { data, error }; normalize both into your own error ref.
  • GraphQL sends a query and variables to one endpoint and may report errors inside a 200 response; Apollo and urql provide useQuery composables.

Next: extending Vue itself with your own directives, Custom Directives.