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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@metadiv-studio/user-auth-context

v0.3.16

Published

A comprehensive React authentication context package that provides user authentication, workspace management, and token handling for multi-tenant applications. Built with TypeScript and designed to work seamlessly with the Metadiv Studio ecosystem.

Readme

@metadiv-studio/user-auth-context

A comprehensive React authentication context package that provides user authentication, workspace management, and token handling for multi-tenant applications. Built with TypeScript and designed to work seamlessly with the Metadiv Studio ecosystem.

📦 Installation

npm i @metadiv-studio/user-auth-context

🎯 What This Package Provides

This package offers a complete authentication solution including:

  • User Authentication: Login, logout, and token management
  • Workspace Management: Multi-tenant workspace support with role-based access
  • Token Handling: Automatic token refresh and storage management
  • Context Provider: React Context-based state management
  • TypeScript Support: Full type definitions for all components and APIs

🚀 Quick Start

1. Wrap Your App with the Provider

import { UserAuthProvider } from '@metadiv-studio/user-auth-context';

function App() {
  return (
    <UserAuthProvider>
      <YourAppComponents />
    </UserAuthProvider>
  );
}

2. Use the Authentication Context

import { useUserAuthContext } from '@metadiv-studio/user-auth-context';

function LoginComponent() {
  const { login, user, workspaceMember } = useUserAuthContext();

  const handleLogin = async () => {
    try {
      await login('[email protected]', 'password123');
      console.log('Login successful!');
    } catch (error) {
      console.error('Login failed:', error);
    }
  };

  return (
    <div>
      {user ? (
        <p>Welcome, {user.display_name}!</p>
      ) : (
        <button onClick={handleLogin}>Login</button>
      )}
    </div>
  );
}

🔧 API Reference

UserAuthProvider

The main context provider that wraps your application and provides authentication state.

<UserAuthProvider>
  {children}
</UserAuthProvider>

useUserAuthContext Hook

Returns the authentication context with the following properties and methods:

State Properties

  • user: SystemUserDTO | null - Current authenticated user
  • workspaceMember: WorkspaceMemberDTO | null - Current workspace member
  • selfWorkspaces: WorkspaceMemberDTO[] - List of user's workspaces

Methods

  • login(usernameOrEmail: string, password: string): Promise<void> - Authenticate user
  • refreshToken(): Promise<boolean> - Refresh authentication token
  • listWorkspaces(): Promise<void> - Fetch user's workspaces
  • getWorkspace(): WorkspaceMemberDTO | null - Get current workspace

📖 Usage Examples

Basic Authentication Flow

import { useUserAuthContext } from '@metadiv-studio/user-auth-context';

function AuthExample() {
  const { 
    user, 
    login, 
    logout, 
    workspaceMember, 
    listWorkspaces 
  } = useUserAuthContext();

  useEffect(() => {
    if (user) {
      // Load user's workspaces when authenticated
      listWorkspaces();
    }
  }, [user]);

  if (!user) {
    return (
      <div>
        <h2>Please Login</h2>
        <button onClick={() => login('[email protected]', 'password')}>
          Login
        </button>
      </div>
    );
  }

  return (
    <div>
      <h2>Welcome, {user.display_name}!</h2>
      <p>Email: {user.email}</p>
      <p>Username: {user.username}</p>
      
      {workspaceMember && (
        <div>
          <h3>Current Workspace</h3>
          <p>Name: {workspaceMember.workspace?.name}</p>
          <p>Role: {workspaceMember.role}</p>
        </div>
      )}
    </div>
  );
}

Workspace Management

import { useUserAuthContext } from '@metadiv-studio/user-auth-context';

function WorkspaceSelector() {
  const { selfWorkspaces, getWorkspace, refreshToken } = useUserAuthContext();
  const currentWorkspace = getWorkspace();

  const handleWorkspaceChange = async (workspaceId: number) => {
    // Refresh token for the new workspace
    const success = await refreshToken();
    if (success) {
      console.log('Workspace changed successfully');
    }
  };

  return (
    <div>
      <h3>Select Workspace</h3>
      <select 
        value={currentWorkspace?.id || ''} 
        onChange={(e) => handleWorkspaceChange(Number(e.target.value))}
      >
        {selfWorkspaces.map(workspace => (
          <option key={workspace.id} value={workspace.id}>
            {workspace.workspace?.name} ({workspace.role})
          </option>
        ))}
      </select>
    </div>
  );
}

Protected Routes

import { useUserAuthContext } from '@metadiv-studio/user-auth-context';

function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const { user, workspaceMember } = useUserAuthContext();

  if (!user) {
    return <div>Please log in to access this page.</div>;
  }

  if (!workspaceMember) {
    return <div>Please select a workspace to continue.</div>;
  }

  return <>{children}</>;
}

// Usage
function App() {
  return (
    <UserAuthProvider>
      <ProtectedRoute>
        <Dashboard />
      </ProtectedRoute>
    </UserAuthProvider>
  );
}

🏗️ Data Models

SystemUserDTO

interface SystemUserDTO {
  id: number;
  created_at: number;
  updated_at: number;
  uuid: string;
  avatar: string;
  username: string;
  email: string;
  display_name: string;
  language: string;
  active: boolean;
  invited: boolean;
  invited_at: number;
}

WorkspaceMemberDTO

interface WorkspaceMemberDTO {
  id: number;
  created_at: number;
  updated_at: number;
  workspace?: WorkspaceDTO;
  user?: SystemUserDTO;
  role: string;
  active: boolean;
  invited: boolean;
}

WorkspaceDTO

interface WorkspaceDTO {
  id: number;
  created_at: number;
  updated_at: number;
  uuid: string;
  avatar: string;
  name: string;
  time_zone: string;
  active: boolean;
}

🔐 Authentication Flow

  1. Login: User provides credentials → API call → Store token and user data
  2. Token Refresh: Automatic token refresh when needed
  3. Workspace Selection: User selects workspace → Refresh token for workspace context
  4. State Persistence: User and workspace data stored in localStorage
  5. Automatic Cleanup: Invalid tokens and expired sessions handled automatically

🛠️ Dependencies

This package requires the following peer dependencies:

  • react ^18
  • react-dom ^18

And includes these internal dependencies:

  • @metadiv-studio/axios-configurator - HTTP client configuration
  • @metadiv-studio/button - UI button component
  • @metadiv-studio/context - Context creation utilities

🎨 Styling

The package includes a Badge component that can be styled with Tailwind CSS classes:

import { Badge } from '@metadiv-studio/user-auth-context';

function UserBadge() {
  return (
    <Badge className="bg-blue-500 text-white">
      Premium User
    </Badge>
  );
}

🔧 Configuration

The package automatically handles:

  • Local Storage Keys: Access tokens, user data, and workspace information
  • API Endpoints: Authentication and workspace management endpoints
  • Error Handling: Graceful fallbacks for failed requests
  • Token Management: Automatic refresh and cleanup

🚨 Error Handling

All authentication methods include proper error handling:

const { login } = useUserAuthContext();

try {
  await login('[email protected]', 'password');
} catch (error) {
  // Handle login errors
  console.error('Authentication failed:', error);
}

📱 Browser Support

  • Modern browsers with ES6+ support
  • React 18+ applications
  • TypeScript 5+ projects

🤝 Contributing

This package is part of the Metadiv Studio ecosystem. For issues, feature requests, or contributions, please refer to the main Metadiv Studio repository.

📄 License

UNLICENSED - See package.json for details.


Built with ❤️ by the Metadiv Studio Team