Add authentication to a React single-page application using MonoCloud.
In this quickstart, you will:
<MonoCloudAuthProvider> so callbacks are handled for youBefore you begin, make sure you have:
npm create vite@latest react-quickstart -- --template react-ts)A complete working example is available at: https://github.com/monocloud/react-quickstart
http://localhost:5173http://localhost:5173http://localhost:5173Keep this tab open. You'll need the Domain and Client ID next.
Install the SDK:
npm install @monocloud/auth-react
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.
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>
);
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.
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;
Start the Vite development server:
npm run dev
Open http://localhost:5173 and:
Your React application is now authenticated with MonoCloud.