npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@optare/optareid-react

v0.1.10

Published

React Hooks and Components for Optare ID

Readme

@optare/optareid-react

React hooks and components for Optare ID authentication.

Installation

npm install @optare/optareid-react
# or
yarn add @optare/optareid-react
# or
pnpm add @optare/optareid-react

Quick Start

1. Wrap your app with OptareProvider

// src/main.tsx
import { OptareProvider } from '@optare/optareid-react';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <OptareProvider
      domain="https://id.optare.one"
      clientId={import.meta.env.VITE_OPTARE_CLIENT_ID}
      redirectUri={window.location.origin}
    >
      <App />
    </OptareProvider>
  </React.StrictMode>
);

2. Use the hook in your components

import { useOptare, SignInButton, LogoutButton } from '@optare/optareid-react';

function App() {
  const { isAuthenticated, isLoading, user, error } = useOptare();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      {isAuthenticated ? (
        <>
          <h1>Welcome, {user?.name}!</h1>
          <LogoutButton />
        </>
      ) : (
        <SignInButton />
      )}
    </div>
  );
}

API Reference

OptareProvider Props

| Prop | Type | Description | |------|------|-------------| | domain | string | Optare ID domain (default: https://id.optare.one) | | clientId | string | Your OAuth Client ID | | redirectUri | string | OAuth callback URL (default: window.location.origin) | | scopes | string[] | OAuth scopes (default: ['openid', 'profile', 'email']) | | audience | string | API audience for token requests | | onAuthComplete | (user: User) => void | Called when authentication completes | | onError | (error: Error) => void | Called when an error occurs | | onRedirectCallback | (appState?) => void | Called after OAuth redirect |

useOptare() Hook

const {
  client,              // OptareClient instance
  user,                // User object
  isAuthenticated,     // boolean
  isLoading,          // boolean
  error,              // Error | null
  login,              // (options?) => void
  logout,             // (options?) => Promise<void>
  getAccessToken,     // () => Promise<string | null>
  getAccessTokenSilently, // (options?) => Promise<string>
} = useOptare();

Components

SignInButton

import { SignInButton } from '@optare/optareid-react';

<SignInButton label="Sign in" />

LogoutButton

import { LogoutButton } from '@optare/optareid-react';

<LogoutButton label="Log out" returnTo="/" />

ProtectedRoute

Protects children, redirecting to login if not authenticated.

import { ProtectedRoute } from '@optare/optareid-react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/dashboard" element={
    <ProtectedRoute>
      <Dashboard />
    </ProtectedRoute>
  } />
</Routes>

Props:

  • loadingComponent - Custom loading component
  • redirectingComponent - Custom redirecting component
  • fallback - Show instead of redirecting (for conditional rendering)
  • returnTo - URL to return to after login

Advanced Usage

Protecting Routes with React Router

import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { useOptare, ProtectedRoute } from '@optare/optareid-react';

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/profile" element={
          <ProtectedRoute>
            <Profile />
          </ProtectedRoute>
        } />
        <Route path="/dashboard" element={
          <ProtectedRoute 
            loadingComponent={<p>Checking authentication...</p>}
          >
            <Dashboard />
          </ProtectedRoute>
        } />
      </Routes>
    </BrowserRouter>
  );
}

Calling Protected APIs

import { useOptare } from '@optare/optareid-react';

function ApiCall() {
  const { getAccessTokenSilently } = useOptare();
  const [data, setData] = useState(null);

  const callProtectedApi = async () => {
    try {
      const token = await getAccessTokenSilently();
      
      const response = await fetch('/api/protected', {
        headers: {
          Authorization: `Bearer ${token}`
        }
      });
      
      const result = await response.json();
      setData(result);
    } catch (error) {
      console.error('API call failed:', error);
    }
  };

  return (
    <div>
      <button onClick={callProtectedApi}>Call API</button>
      {data && <pre>{JSON.stringify(data, null, 2)}</pre>}
    </div>
  );
}

Using Higher-Order Components

import { withAuthenticationRequired } from '@optare/optareid-react';

function Dashboard() {
  return <div>Protected Dashboard Content</div>;
}

// Wrap component to require authentication
const ProtectedDashboard = withAuthenticationRequired(Dashboard, {
  onLoading: () => <p>Loading...</p>,
  onRedirecting: () => <p>Redirecting to login...</p>,
  returnTo: '/dashboard'
});

export default ProtectedDashboard;

Custom useAuthenticatedUser Hook

import { useAuthenticatedUser } from '@optare/optareid-react';

function UserDashboard() {
  const { user, accessToken, isLoading } = useAuthenticatedUser();

  if (isLoading) return <div>Loading...</div>;

  return (
    <div>
      <h1>Welcome, {user?.name}</h1>
      <p>Token: {accessToken ? 'Available' : 'Not available'}</p>
    </div>
  );
}

Using fetchWithAuth Utility

import { useOptare, fetchWithAuth } from '@optare/optareid-react';

function DataFetcher() {
  const { getAccessTokenSilently } = useOptare();
  
  const loadData = async () => {
    const response = await fetchWithAuth(
      '/api/data',
      { method: 'GET' },
      getAccessTokenSilently
    );
    return response.json();
  };
}

Environment Variables

# Required
VITE_OPTARE_CLIENT_ID=your_client_id

# Optional
VITE_OPTARE_DOMAIN=https://id.optare.one

CLI Setup (Recommended)

# Install Optare CLI
npm install -g @optare/optareid-cli

# Login and initialize project
optare login
optare init

This automatically:

  • Creates an OAuth client
  • Configures redirect URLs
  • Generates your .env file

Browser Support

  • Chrome/Edge 90+
  • Firefox 88+
  • Safari 14+

AI Integration

See AI_PROMPT.md for an AI-friendly prompt to integrate Optare in your IDE.

Documentation

Support

License

MIT