The Auth SDK for React enables you to authenticate users using React-specific features.
Getting Started
1. Install the SDK
Install the SDK with your preferred package manager.
npm install @microapp-io/react
2. Wrap Your App with the Provider
In order for your microapp to have access to auth features, it needs to be wrapped in the AuthProvider
component:
import { AuthProvider } from "@microapp-io/react";
function App() {
return <AuthProvider>{/* Your microapp code here */}</AuthProvider>;
}
For local development, we recommend using the sandbox
feature on the AuthProvider
component to return mocked users:
import { AuthProvider } from "@microapp-io/react";
const sandbox = {
enabled: process.env.NODE_ENV !== "production",
user: {
id: "1",
email: "[email protected]",
pictureUrl: "https://example.com/avatar.png",
},
};
function App() {
return (
<AuthProvider sandbox={sandbox}>
{/* Your microapp code here */}
</AuthProvider>
);
}
The sandbox
prop should only be used for local development. Do not use it in
production.
3. Use the useAuth
Hook
The useAuth
hook returns all of the auth data and methods available to your microapp. It returns the following type:
type Auth = {
isAuthenticated: boolean;
isLoading: boolean;
user?: {
id: string;
email: string;
pictureUrl: string;
};
error?: Error;
refresh: () => void;
requestLogin: () => void;
};
4. Prompt the User to Log In
You can prompt the user to log in by calling the requestLogin
method.
import { useAuth } from '@microapp-io/react';
function Home() {
const { requestLogin } = useAuth();
return (
<button onClick={() => requestLogin()}>Log In</button>
);
}
5. Get Notified when the Authenticated User Changes
You can get notified when the authenticated user changes passing a callback on Auth initialization
import { useAuth } from '@microapp-io/react';
function Home() {
const { requestLogin } = useAuth({
onChange: (user) => console.log('Auth user changed', user),
});
requestLogin();
}
6. Example Usage
Here is an example of how you can use the useAuth
hook in your microapp:
import { useAuth } from "@microapp-io/react";
function Home() {
const {
isAuthenticated,
isLoading,
user,
error,
requestLogin,
} = useAuth({
onChange: (user) => console.log('Auth user changed', user),
});
if (isLoading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error.message}</p>;
}
if (!isAuthenticated) {
return <button onClick={() => requestLogin()}>Log In</button>;
}
}