React SDK

Disclaimer: This library is meant to help you with a quick implementation of the LoginRadius platform and also to serve as a reference point for the LoginRadius API. Keep in mind that it is an open source library, which means you are free to download and customize the library functions based on your specific application needs.

This document describes how to start using the LoginRadius React SDK for the various authentication types and features supported by the LoginRadius Identity Platform’s. You can get the SDK from here.

For a more hands-on tutorial on setting up the SDK and using it in an React application to make LoginRadius API calls, check out our React Tutorial.

Installation

Using npm

npm install loginradius-react

Getting Started

Configure the SDK by wrapping your application in LRAuthProvider:

// src/index.js
import React from "react"
import ReactDOM from "react-dom"
import App from "./App"
import { LRAuthProvider } from "loginradius-react"

ReactDOM.render(
  <React.StrictMode>
    <LRAuthProvider
      appName="YOUR_LOGINRADIUS_APPNAME"
      apiKey="YOUR_LOGINRADIUS_APIKEY"
      redirectUri={window.location.origin}
    >
      <App />
    </LRAuthProvider>
  </React.StrictMode>,
  document.getElementById("root")
)

Use the useLRAuth hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.js
import React from "react"
import { useLRAuth } from "loginradius-react"

function App() {
  const {
    isLoading,
    isAuthenticated,
    error,
    user,
    loginWithRedirect,
    logout,
  } = useLRAuth()

  if (isLoading) {
    return <div>Loading...</div>
  }
  if (error) {
    return <div>Oops... {error.message}</div>
  }

  if (isAuthenticated) {
    return (
      <div>
        Hello {user.name}{" "}
        <button onClick={() => logout({ returnTo: window.location.origin })}>
          Log out
        </button>
      </div>
    )
  } else {
    return <button onClick={loginWithRedirect}>Log in</button>
  }
}

export default App

Protect a Route

Protect a route component using the withAuthenticationRequired higher order component. Visits to this route when unauthenticated will redirect the user to the login page and back to this page after login:

import React from "react"
import { withAuthenticationRequired } from "loginradius-react"

const PrivateRoute = () => <div>Private</div>

export default withAuthenticationRequired(PrivateRoute, {
  // Show a message while the user waits to be redirected to the login page.
  onRedirecting: () => <div>Redirecting you to the login page...</div>,
})

Call an API

Call a protected API with an Access Token:

import React, { useEffect, useState } from "react";
import { useLRAuth } from "loginradius-react";

const CallAPI = () => {
  const { getAccessTokenSilently } = useLRAuth();
  const [resp setResp] = useState(null);

  useEffect(() => {
    (async () => {
      try {
        const token = await getAccessTokenSilently();
        const response = await fetch(
          `https://api.loginradius.com/identity/v2/auth/access_token/validate?access_token=${token}&apiKey=${process.env.REACT_APP_API_KEY}`,
          {}
        );
        setResp(await response.json());
      } catch (e) {
        console.error(e);
      }
    })();
  }, [getAccessTokenSilently]);

  if (!resp) {
    return <div>Loading...</div>;
  }

  return (
    <span>{JSON.stringify(state.resp, null, 2)}</span>
  );
};

export default CallAPI;