Navigation

MongoDB Realm - React Quickstart

Deployment Type:

Author: MongoDB Documentation Team

This guide shows you how to set up a basic React web application that connects to your MongoDB Realm app and authenticates an anonymous user.

We put together a finished version of this quickstart on CodeSandbox. All you have to do is paste in your Realm App ID to connect to your app.

Time required: 10 minutes

What You’ll Need

This guide assumes that you have already created a MongoDB Realm application and enabled anonymous authentication. For details on how to do this, see Create a Realm App and Enable Anonymous Authentication.

Check Your Environment

To create and run this application you will need npm installed on your machine.

The create-react-app documentation recommends that you install npx to run create-react-app rather than using a version that’s installed on your machine.

Procedure

1

Set up a New React App

Generate a new application template using create-react-app:

npx create-react-app realm-web-react-quickstart --template=typescript
npx create-react-app realm-web-react-quickstart

Navigate into the new app and install the realm-web package:

cd realm-react-quickstart
yarn add realm-web
2

Import Dependencies & Connect to Your Realm App

The Realm Web SDK contains everything you need to connect to a MongoDB Realm application from a browser application. In /src/App.js, add the following code that imports the Web SDK and uses it to instantiate a new Realm.App object:

import * as Realm from "realm-web";

const REALM_APP_ID = "<Your App ID>"; // e.g. myapp-abcde
const app: Realm.App = new Realm.App({ id: REALM_APP_ID });
import * as Realm from "realm-web";

const REALM_APP_ID = "<Your App ID>"; // e.g. myapp-abcde
const app = new Realm.App({ id: REALM_APP_ID });

The app object represents your Realm app. You’ll use it to authenticate and manage the users that interact with your app.

3

Create React Components

In /src/App.js, add the following components that display details about a given user and allow users to log in.

// Create a component that displays the given user's details
const UserDetail: React.FC<{ user: Realm.User }> = ({ user }) => {
  return (
    <div>
      <h1>Logged in with anonymous id: {user.id}</h1>
    </div>
  );
}

// Create a component that lets an anonymous user log in
const Login: React.FC<{ setUser: (user: Realm.User) => void }> = ({ setUser }) => {
  const loginAnonymous = async () => {
    const user: Realm.User = await app.logIn(Realm.Credentials.anonymous());
    setUser(user);
  };
  return <button onClick={loginAnonymous}>Log In</button>;
}
// Create a component that displays the given user's details
function UserDetail({ user }) {
  return (
    <div>
      <h1>Logged in with anonymous id: {user.id}</h1>
    </div>
  );
}

// Create a component that lets an anonymous user log in
function Login({ setUser }) {
  const loginAnonymous = async () => {
    const user = await app.logIn(Realm.Credentials.anonymous());
    setUser(user);
  };
  return <button onClick={loginAnonymous}>Log In</button>;
}
4

Create and Export the App Component

In /src/App.js, overwrite the existing App component with the following component that stores the current user in local state and conditionally renders either details about the current user or a login screen if no user is currently authenticated.

const App: React.FC = () => {
  // Keep the logged in Realm user in local state. This lets the app re-render
  // whenever the current user changes (e.g. logs in or logs out).
  const [user, setUser] = React.useState<Realm.User | null>(app.currentUser);

  // If a user is logged in, show their details. Otherwise, show the login screen.
  return (
    <div className="App">
      <div className="App-header">
        {user ? <UserDetail user={user} /> : <Login setUser={setUser} />}
      </div>
    </div>
  );
}

export default App;
const App = () => {
  // Keep the logged in Realm user in local state. This lets the app re-render
  // whenever the current user changes (e.g. logs in or logs out).
  const [user, setUser] = React.useState(app.currentUser);

  // If a user is logged in, show their details.
  // Otherwise, show the login screen.
  return (
    <div className="App">
      <div className="App-header">
        {user ? <UserDetail user={user} /> : <Login setUser={setUser} />}
      </div>
    </div>
  );
}

export default App;
5

Run the App

You’re now ready to connect to your Realm app and log in! Make sure you’ve saved your changes to /src/App.js and then run the following command from the project root:

yarn start

This starts a local web server that serves your application. If successful, you should see the following output in your shell:

Compiled successfully!

You can now view realm-quickstart-web in the browser.

  Local:  http://localhost:3000

Open http://localhost:3000 in your browser and test that you can successfully log in as an anonymous user.

Summary

If you have successfully completed this guide, you have created a React application that can connect to a MongoDB Realm app and authenticates an anonymous user.

What’s Next

Want to build more with Realm? Check out the official MongoDB Realm documentation for hands-on tutorials, conceptual overviews, and detailed reference information.