Docs Menu

Docs HomeRealm

Apollo Client (React)

On this page

  • Overview
  • Set Up Apollo Client
  • Install Dependencies
  • Import dependencies
  • Create an Apollo GraphQL Client
  • Set Up User Authentication
  • Add the Apollo Client to Your App
  • Run Queries and Mutations
  • Run a Query
  • Run a Mutation

You can use Apollo Client to connect to your Realm app's exposed GraphQL API from a React application. Apollo Client runs queries and mutations, maintains a client-side data cache, and integrates into your app with idiomatic React components and hooks.


See a Working Demo Application

Check out the Realm GraphQL - Apollo (React) repository on GitHub to see a fully set-up React & Apollo application that's ready to connect to your own Atlas App Services backend. It uses the sample_mflix.movies collection that's included in the MongoDB Atlas sample data sets.

If you don't want to clone the repository, the demo application is also available in-browser in the Realm GraphQL CodeSandbox.


As in any Realm project, you'll need to install the Realm Web SDK to authenticate users and requests.

npm install realm-web

Apollo bundles the core components that you need to create a client in a package called @apollo/client. It also requires the graphql package to parse GraphQL queries.

npm install @apollo/client graphql

Import the necessary dependencies from realm-web and @apollo/client to create your Apollo GraphQL client and add authentication with Realm.

import * as Realm from "realm-web";
import {
} from "@apollo/client";

Create a new ApolloClient object that points to your Realm app's GraphQL API endpoint. You generate the endpoint URL based on your Realm App ID or find it on the GraphQL page of the Realm UI.

// Add your Realm App ID
const graphqlUri = `${APP_ID}/graphql`;
// Local apps should use a local URI!
// const graphqlUri = `${APP_ID}/graphql`
// const graphqlUri = `${APP_ID}/graphql`
// const graphqlUri = `${APP_ID}/graphql`
const client = new ApolloClient({
link: new HttpLink({
uri: graphqlUri,
cache: new InMemoryCache(),

The ApolloClient is configured to send requests to your app. However, all Realm GraphQL requests must include a valid user access token to authenticate requests, so right now any operations sent from Apollo will fail.

To authenticate requests, you need to add an Authorization header with a valid Realm user access token to each GraphQL request.

You can authenticate a user and get their access token with the Realm Web SDK. The Apollo HttpLink object allows you to add custom headers to every request by defining a custom fetch function.

// Connect to your MongoDB Realm app
const app = new Realm.App(APP_ID);
// Gets a valid Realm user access token to authenticate requests
async function getValidAccessToken() {
// Guarantee that there's a logged in user with a valid access token
if (!app.currentUser) {
// If no user is logged in, log in an anonymous user. The logged in user will have a valid
// access token.
await app.logIn(Realm.Credentials.anonymous());
} else {
// An already logged in user's access token might be stale. To guarantee that the token is
// valid, we refresh the user's custom data which also refreshes their access token.
await app.currentUser.refreshCustomData();
return app.currentUser.accessToken;
// Configure the ApolloClient to connect to your app's GraphQL endpoint
const client = new ApolloClient({
link: new HttpLink({
uri: `${APP_ID}/graphql`,
// We define a custom fetch handler for the Apollo client that lets us authenticate GraphQL requests.
// The function intercepts every Apollo HTTP request and adds an Authorization header with a valid
// access token before sending the request.
fetch: async (uri, options) => {
const accessToken = await getValidAccessToken();
options.headers.Authorization = `Bearer ${accessToken}`;
return fetch(uri, options);
cache: new InMemoryCache(),

The Apollo client object is now configured to send authenticated GraphQL requests to your App Services backend. All that's left to do is make it available to the rest of your React application.

The @apollo/client package exports an ApolloProvider component that makes the client available to any Apollo hooks that you call from child components. Wrap your app in an ApolloProvider and pass the client object to the provider.

// ... code to create the GraphQL client
const AppWithApollo = () => (
<ApolloProvider client={client}>
<App />

The @apollo/client package includes a set of declarative React hooks that connect your components to the GraphQL API and handle query and mutation execution.

To define queries and mutations that you can pass to the hooks, install graphql-tag:

npm install graphql-tag

Import the relevant hooks and the GraphQL query constructor at the top of the file where you're using them.

// import whichever Apollo hooks you're using
import { useQuery, useMutation } from "@apollo/client";
import gql from "graphql-tag";


Apollo Hooks Must Have An ApolloProvider

Components that call the query and mutation hooks must be descendants of the ApolloProvider that you configured for your App Services backend. The hooks call the query and mutation methods on the provided client object.

Apollo Client includes two hooks for executing queries. The hooks accept identical parameters but differ in when they execute the query:

  • useQuery() runs automatically when its component mounts. It also returns a callback that re-runs the query whenever you call it.

  • useLazyQuery() returns a callback function that executes the query whenever you call it. It does not run the query on component mount.

Both hooks accept a query definition and additional options, including variables that Apollo passes to the query. They also both return information about the query's current execution status and data returned from the most recent execution.

const ALL_MOVIES = gql`
query AllMovies {
movies {
// Must be rendered inside of an ApolloProvider
function Movies() {
const { loading, error, data } = useQuery(ALL_MOVIES);
if (loading) {
return <div>loading</div>;
if (error) {
return <div>encountered an error: {error}</div>;
return <MovieList movies={data.movies} />;

The useMutation() hook accepts a mutation definition and an optional configuration object. The most common option you'll need to pass is a variables object that maps to GraphQL variables in the mutation definition.

The hook returns several objects in an array:

  • a callback function that executes the mutation

  • an object that includes information on the mutation's execution status and data returned from the most recent execution.

mutation UpdateMovieTitle($oldTitle: String!, $newTitle: String!) {
updateOneMovie(query: { title: $oldTitle }, set: { title: $newTitle }) {
// Must be rendered inside of an ApolloProvider
function MovieList({ movies }) {
const [updateMovieTitle] = useMutation(UPDATE_MOVIE_TITLE);
return (
{ => (
<li key={movie._id}>
onClick={() => {
variables: {
oldTitle: movie.title,
newTitle: "Some New Title",
Update Title
←  Query MongoDBAPI Reference - Web SDK →
Give Feedback
© 2022 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.