Sign in

React Quickstart

Add authentication to a React single-page application using MonoCloud.

In this quickstart, you will:

  • Create a MonoCloud Single Page App
  • Install the MonoCloud React SDK
  • Wrap your app with the <MonoCloudAuthProvider> so callbacks are handled for you
  • Read the authenticated user and add sign-in, sign-up, and sign-out actions

Prerequisites

Before you begin, make sure you have:

  • A MonoCloud account and tenant
  • Node.js 18+ (npm, Yarn, or PNPM)
  • An existing Vite + React project (or run npm create vite@latest react-quickstart -- --template react-ts)
A complete working example is available at: https://github.com/monocloud/react-quickstart

Configure MonoCloud

  1. In the MonoCloud Dashboard, create a new Single Page App
  2. Select React as your stack
  3. Set the following URLs for local development (assuming the Vite default port):
    • Callback URLs: http://localhost:5173
    • Sign-out URLs: http://localhost:5173
    • Cross-Origin URLs: http://localhost:5173
Keep this tab open. You'll need the Domain and Client ID next.

Install the SDK

Install the SDK:

Terminal
npm install @monocloud/auth-react

Wrap your app with the provider

Wrap your application with <MonoCloudAuthProvider> in src/main.tsx. The provider initializes the client and, by default, completes the sign-in and sign-out callbacks automatically when it mounts.

src/main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { MonoCloudAuthProvider } from "@monocloud/auth-react";
import App from "./App.tsx";

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <MonoCloudAuthProvider
      tenantDomain="https://<your-domain>"
      clientId="<your-client-id>"
    >
      <App />
    </MonoCloudAuthProvider>
  </StrictMode>
);

Add the authentication code

Replace src/App.tsx with the following. It reads the authentication state with useAuth() and wires up the sign-in, sign-up, and sign-out buttons.

src/App.tsx
import { useAuth, SignIn, SignUp, SignOut } from "@monocloud/auth-react";

function App() {
  const { isLoading, isAuthenticated, user } = useAuth();

  if (isLoading) {
    return <p>Loading...</p>;
  }

  if (!isAuthenticated) {
    return (
      <>
        <SignIn>Sign In</SignIn>
        <SignUp>Sign Up</SignUp>
      </>
    );
  }

  return (
    <>
      <pre>{JSON.stringify(user, null, 2)}</pre>
      <SignOut>Sign Out</SignOut>
    </>
  );
}

export default App;

Run the application

Start the Vite development server:

Terminal
npm run dev

Open http://localhost:5173 and:

  • Click Sign In to authenticate with MonoCloud
  • After redirecting back, the user object renders on the page
  • Click Sign Out to end the session

Your React application is now authenticated with MonoCloud.

© 2024 MonoCloud. All rights reserved.