🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

GraphQL in the Browser: Queries, Mutations, Subscriptions

Web FoundationsAPIsđŸŸĸ Free Lesson

GraphQL in the Browser: Queries, Mutations, Subscriptions

GraphQL is a query language for APIs and a runtime for executing those queries against a typed schema. From the browser's point of view it collapses many REST endpoints into one URL: you POST a query document describing exactly the data shape you need, the server responds with exactly that shape, and the schema guarantees the types on both sides. The appeal is obvious when a screen needs a user, their last five orders, and each order's line items — three REST round trips or three hand-written endpoints, versus one GraphQL query.

The costs are equally real: a public query surface needs depth limiting and query cost analysis to stay safe, HTTP caching does not apply the way you expect, and the N+1 resolver problem can make a pretty query slow. This lesson covers the browser-side mechanics completely and flags the trade-offs as they appear in production.

One Endpoint, Typed Documents

Every GraphQL request is a POST to a single endpoint with a JSON body containing the query string and optional variables. The simplest client needs nothing but fetch:

javascript
async function graphql(query, variables = {}, headers = {}) {
  const response = await fetch('/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Client': 'web-app',
      ...headers
    },
    body: JSON.stringify({ query, variables })
  });

  const payload = await response.json();
  if (payload.errors && !payload.data) {
    throw new GraphQLError(payload.errors);
  }
  return payload;
}

const DOCUMENT = `
  query RecentOrders($first: Int!) {
    viewer {
      id
      name
      orders(first: $first) {
        edges {
          node {
            id
            total
            placedAt
            status
          }
        }
      }
    }
  }
`;

const { data, errors } = await graphql(DOCUMENT, { first: 5 });
if (errors) showPartialWarning(errors);
renderOrders(data.viewer.orders.edges.map((edge) => edge.node));

Note the variables: the first argument to graphql is always a constant string, and user-supplied values travel through the variables map. Building queries by pasting strings together is the GraphQL equivalent of SQL injection — the variables mechanism exists precisely so the query document never contains untrusted data. Also note that a response can carry both data and errors simultaneously; the branch above throws only when there is no data at all.

Mutations and Input Types

Mutations follow the same transport with a different keyword, and they declare variables with input types whose fields are required or optional in the same syntax as query variables:

javascript
const CREATE_ORDER = `
  mutation CreateOrder($input: CreateOrderInput!) {
    createOrder(input: $input) {
      order {
        id
        total
        placedAt
      }
      userErrors {
        field
        message
      }
    }
  }
`;

async function submitOrder(cart) {
  const result = await graphql(CREATE_ORDER, {
    input: {
      lineItems: cart.items.map((item) => ({
        productId: item.productId,
        quantity: item.quantity
      }))
    }
  });

  const { order, userErrors } = result.data.createOrder;
  if (userErrors.length > 0) {
    showFormErrors(userErrors);
    return null;
  }
  return order;
}

Business-rule failures — an out-of-stock product, a declined card — usually arrive in a userErrors array with a field path, not as HTTP 4xx responses. The distinction matters for UI: transport and authorization problems throw, validation problems render into the form beside the offending input. Keep that split consistent so error handling code does not grow a maze of special cases.

The Error Contract

SituationHTTP statusResponse body
Well-formed query, full success200data only
Partial failure in a nullable field200data with some nulls plus errors array
Malformed query document400errors only
Auth or validation failure before execution400 or 401errors, sometimes partial data
Unhandled server exception500errors only

Because GraphQL reports execution errors in the body with a 200 status, response.ok alone will not protect you — parse the payload and check the errors key. The errors array entries carry a message, a path into the data, and often structured extensions with codes; log the paths, because they tell you which resolver failed without a server log dive.

Fragments and Reusable Selections

Fragments name a selection set once and reuse it across queries, which keeps type-ahead component props and server responses in lockstep:

fragment OrderFields on Order {
  id
  total
  placedAt
  status
}

query Dashboard {
  viewer {
    recent: orders(first: 3) {
      edges { node { ...OrderFields } }
    }
    pending: orders(first: 5, status: PENDING) {
      edges { node { ...OrderFields } }
    }
  }
}

Aliases let one query request the same field twice with different arguments, as the dashboard example shows. Together, fragments and aliases make it practical to keep one query document per screen, which is the organizational model most GraphQL codebases converge on.

The schema's type system is what makes those documents checkable before they ever hit the network. Scalar types cover primitives; object types compose; interface and union types describe values that may be one of several shapes; and enums constrain arguments to a fixed set. Every field also carries nullability, and that nullability is part of the contract: if a field is nullable, the server may legally return it as null inside a successful response, which is exactly how the partial-failure case arises. Generate TypeScript types from the introspection schema in CI so a renamed field breaks the build instead of a customer's dashboard.

Subscriptions: Real-Time Over a Socket

Subscriptions cannot ride ordinary fetch; they need a persistent connection, classically a WebSocket running the graphql-ws protocol. The client sends a subscribe message carrying the query, and the server pushes a stream of data messages until the client stops the operation. The browser-side shape is a function returning an unsubscribe:

javascript
function subscribeToOrderUpdates(onEvent) {
  const socket = new WebSocket('wss://api.example.com/graphql');
  const id = '1';

  socket.onopen = () => {
    socket.send(JSON.stringify({ type: 'connection_init', payload: {} }));
    socket.send(JSON.stringify({
      id,
      type: 'subscribe',
      payload: {
        query: `
          subscription OnOrderChanged {
            orderChanged { id status placedAt }
          }
        `
      }
    }));
  };

  socket.onmessage = (event) => {
    const message = JSON.parse(event.data);
    if (message.type === 'data') onEvent(message.payload.data.orderChanged);
  };

  return () => socket.close();
}

Newer protocols swap the message vocabulary for ping-pong heartbeats and explicit complete messages; the shape stays the same. If your real-time needs are one-directional and simple, Server-Sent Events plus a REST endpoint is often less machinery than a full subscription stack.

Whichever transport you choose, treat subscription lifecycle with the same discipline as the WebSocket lesson: reconnect with backoff, re-subscribe after every open, and make the UI honest about connection state. A dashboard whose prices silently froze two minutes ago is worse than one that visibly says it is reconnecting, because the user cannot tell which numbers are real.

When GraphQL Is the Wrong Tool

ScenarioPrefer
Simple CRUD with stable, cacheable resourcesREST
Highly cacheable public data at the CDNREST
Screens composing nested, varying data shapesGraphQL
File uploads, downloads, streamingREST endpoints
Teams small enough to know every endpointEither — pick the simpler one

The N+1 problem deserves emphasis because it is the performance bug unique to this architecture: a query that asks for authors and their posts can trigger one database query for the author list and then one query per author for posts, unless the server applies dataloader-style batching. You cannot fix this from the browser, which is why evaluating a GraphQL backend means asking how it batches, not only how it types. On the client side, add depth and cost limits to any public endpoint, persist queries where the network cost of shipping large documents matters, and use a client library — Apollo Client, urql, or Relay — once you have more than a handful of screens, because normalized caching and request deduplication are exactly the problems those tools solved so you do not have to.

Before adopting GraphQL at all, walk one candidate screen through both designs. If its data is a single nested resource that maps cleanly onto a handful of cached REST endpoints, GraphQL adds a query language, a build step, and a caching model your team must learn for little gain. If the same screen is assembled from three endpoints with over-fetching on every one of them, and mobile network costs are a product concern, the trade flips. The technology is a tool for a specific data-shape problem, and the strongest GraphQL adoptions start from that problem rather than from the novelty of the syntax.

Common Mistakes

Building query strings by interpolating user input

Fix: Always pass untrusted values through the variables map; keep documents constant.

Treating HTTP 200 as success without checking the errors array

Fix: GraphQL reports execution errors in the body — branch on payload.errors, not just response.ok.

Throwing away partial data when one field errors

Fix: Nullable fields fail independently; render what arrived and flag what did not.

One giant query shared by every screen

Fix: Keep a document per screen and reuse fragments for shared selections.

Ignoring resolver depth and batching on the server

Fix: Ask for dataloader-style batching and enforce query depth limits before launch.

Key Takeaways

  • GraphQL is one typed endpoint: POST a query document, get exactly the shape you asked for.
  • Put every user-supplied value in the variables map — string interpolation is an injection risk.
  • Check the errors key on every response; execution failures arrive with HTTP 200.
  • Fragments and aliases organize documents per screen and keep component props honest.
  • Subscriptions need a WebSocket protocol layer; one-directional updates are often better served by SSE.
  • Evaluate a GraphQL backend on batching and depth limits as much as on its type system.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement