Skip to main content

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

PropertyDescription
urlsObject containing URLs for appUrl, apiUrl, graphQLUrl, loginUrl, and natsUrl
requestFunction that wraps fetch(url, options) with automatic MachineMetrics authorization headers and application/json content type
clientIdOAuth client ID of the application
isAuthenticatedBoolean indicating whether usable credentials are present
logoutFunction to log the user out
getCredentialgetCredential(purpose) returns the credential for 'api', 'graphql', or 'nats'. Read per-use; never cache the result.
grantedScopeSpace-delimited scopes actually granted, when known

Reactive reads: getCredential is an imperative one-off read. To re-render a component when a credential changes (e.g. a refresh), use the useCredential(purpose) hook instead. It is exported from the package root next to useMMAuth, takes the same 'api' | 'graphql' | 'nats' purpose, and returns the credential string or null until it has been established.

Migrating from v4? accessTokengetCredential('api'), jwtRef.currentgetCredential('graphql'), natsCredsRef.currentgetCredential('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