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 Stitch 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.

Once your app is 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 Stitch user access token to each GraphQL request. You can get the access token with the Stitch browser 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 mongodb-stitch-browser-sdk

The following code shows how to import the required modules, add Authorization headers to requests, and instantiate an ApolloClient that connects to a Stitch 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";
import App from "./App";
// Apollo
import { ApolloClient, HttpLink, InMemoryCache } from "apollo-boost";
import { setContext } from "apollo-link-context";
// Stitch
import { Stitch, AnonymousCredential } from "mongodb-stitch-browser-sdk";

// Instantiate a StitchClient
// TODO: Replace this with your Stitch App ID
const APP_ID = "myapp-abcde";
const app = Stitch.hasAppClient(APP_ID)
  ? Stitch.getAppClient(APP_ID)
  : Stitch.initializeAppClient(APP_ID);

// Get the logged in user's access token from the StitchAuth interface
async function getAccessToken(credential) {
  if(!app.auth.user) {
    await app.auth.loginWithCredential(credential);
  } else {
    await app.auth.refreshAccessToken();
  }
  const { accessToken } = app.auth.activeUserAuthInfo;
  return accessToken;
}

// Add an Authorization header with a valid user access token to all requests
// NOTE: You can use a credential for any enabled authentication provider
const credential = new AnonymousCredential();
const authorizationHeaderLink = setContext(async (_, { headers }) => {
  const accessToken = await getAccessToken(credential);
  return {
    headers: {
      ...headers,
      Authorization: `Bearer ${accessToken}`,
    },
  };
});

// Construct a new Apollo HttpLink that connects to your app's GraphQL endpoint
const graphql_url = `https://stitch.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(),
});

Add the GraphQL Client to Your App

Apollo provides the @apollo/react-hooks package which contains a set of React hooks that you can use to execute GraphQL operations. The package also contains an ApolloProvider component that make 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"),
);