useMMAuth
Provides access to configured URLs and a request convenience function that makes fetch requests with MachineMetrics authorization headers.
Usage
import { useMMAuth } from '@machinemetrics/mm-react-tools';
function MyWidget() {
const {
urls,
request,
clientId,
isAuthenticated,
logout,
getCredential,
grantedScope,
} = useMMAuth();
// Example usage
const fetchMachines = async () => {
const machines = await request(`${urls.apiUrl}/machines`);
return machines;
};
if (!isAuthenticated) {
return <div>Please log in to view machines</div>;
}
return (
<div>
<h1>Machines</h1>
{/* Use the fetched data */}
</div>
);
}
Properties
| Property | Description |
|---|---|
urls | Object containing URLs for appUrl, apiUrl, graphQLUrl, loginUrl, and natsUrl |
request | Function that wraps fetch(url, options) with automatic MachineMetrics authorization headers and application/json content type |
clientId | OAuth client ID of the application |
isAuthenticated | Boolean indicating whether usable credentials are present |
logout | Function to log the user out |
getCredential | getCredential(purpose) returns the credential for 'api', 'graphql', or 'nats'. Read per-use; never cache the result. |
grantedScope | Space-delimited scopes actually granted, when known |
Reactive reads:
getCredentialis an imperative one-off read. To re-render a component when a credential changes (e.g. a refresh), use theuseCredential(purpose)hook instead. It is exported from the package root next touseMMAuth, takes the same'api' | 'graphql' | 'nats'purpose, and returns the credential string ornulluntil it has been established.Migrating from v4?
accessToken→getCredential('api'),jwtRef.current→getCredential('graphql'),natsCredsRef.current→getCredential('nats').
Example
const { urls, request } = useMMAuth();
// Make an API request
const machines = await request(`${urls.apiUrl}/machines`);
Reactive credential, re-rendering when it changes:
import { useMMAuth, useCredential } from '@machinemetrics/mm-react-tools';
const accessToken = useCredential('api'); // null until the session is established
const { urls } = useMMAuth();
if (!accessToken) return null;
// pass accessToken to anything that needs the bearer, e.g. a host-side credential broker