Navigation

Connect from a Client Application

Overview

You can connect a client application to the GraphQL API to read and write data that you have exposed from a collection. This guide includes example code that demonstrates how to configure a GraphQL client and authenticate requests in common GraphQL libraries and frameworks.

Once you’ve connected your client application, you can begin to execute GraphQL operations.

Run It in CodeSandbox

You can see a working application in your browser in this Realm GraphQL CodeSandbox that we’ve prepared. It uses the sample_mflix.movies collection that’s included in the MongoDB Atlas sample data sets.

To set up your app:

  1. Link a cluster that includes the Atlas sample data sets.
  2. Configure permissions for the sample_mflix.movies collection. For this demo, you can assign full read/write permissions to the default role.
  3. Generate a collection schema for the sample_mflix.movies collection. Add a root-level title field to the schema with the value set to "Movie".
  4. Enable anonymous authentication.
  5. Deploy your changes.

After you complete the app set up, paste your App ID into the CodeSandbox to connect and use the GraphQL API.

Create a GraphQL Client

Apollo Client is a client library that manages connections and data caching for any standard GraphQL API. Apollo packages the core components you need in a single package called apollo-boost.

You also need to add an authentication header that includes a valid Realm user access token to each GraphQL request. You can get the access token with the Realm Web SDK and add the header to every request with the apollo-link-context package.

To install the packages required for request authentication, run the following:

npm install apollo-boost apollo-link-context graphql realm-web

The following code shows how to import the required modules, add Authorization headers to requests, and instantiate an ApolloClient that connects to a Realm GraphQL endpoint. Make sure to set the value of APP_ID with your App ID.

// React
import React from "react";
import { render } from "react-dom";
// Apollo
import { ApolloClient, HttpLink, InMemoryCache } from "apollo-boost";
import { setContext } from "apollo-link-context";
import { ApolloProvider } from "@apollo/react-hooks";
// Realm
import * as RealmWeb from "realm-web";
// Check out app.js for examples of how to run GraphQL operations
import App from "./app";

export const APP_ID = "<Your App ID>";

const app = new RealmWeb.App({
  id: APP_ID,
  baseUrl: "https://realm.mongodb.com"
});

// Add an Authorization header with a valid user access token to all GraphQL requests
const authorizationHeaderLink = setContext(async (_, { headers }) => {
  if (app.currentUser) {
    // Refreshing custom data also refreshes the access token
    await app.currentUser.refreshCustomData();
  } else {
    // If no user is logged in, log in an anonymous user
    await app.logIn(RealmWeb.Credentials.anonymous());
  }
  // Get a valid access token for the current user
  const { accessToken } = app.currentUser;
  console.log("currentUser", accessToken, app.currentUser);

  // Set the Authorization header, preserving any other headers
  return {
    headers: {
      ...headers,
      Authorization: `Bearer ${accessToken}`
    }
  };
});

// Construct a new Apollo HttpLink that connects to your app's GraphQL endpoint
const graphql_url = `https://realm.mongodb.com/api/client/v2.0/app/${APP_ID}/         graphql`;
const httpLink = new HttpLink({ uri: graphql_url });

// Construct a new Apollo client with the links we just defined
const client = new ApolloClient({
  link: authorizationHeaderLink.concat(httpLink),
  cache: new InMemoryCache()
});

render(
  // Wrap your app with an ApolloProvider
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById("root")
);

Add the GraphQL Client to Your App

Apollo provides the @apollo/react-hooks package that contains a set of React hooks you can use to execute GraphQL operations. The package also contains an ApolloProvider component that makes your ApolloClient available to all components in your app.

To install the package, run the following:

npm install @apollo/react-hooks

Wrap your React application with an ApolloProvider and pass the client that you created to the provider as a prop. Any components rendered inside of the ApolloProvider can use Apollo React hooks.

import { ApolloProvider } from "@apollo/react-hooks";

// ... code to create the GraphQL client

render(
  <ApolloProvider client={client}>
     <App />
  </ApolloProvider>,
  document.getElementById("root"),
);