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

react-permission-guard

v1.3.2

Published

A React permission system for managing access control in applications

Downloads

40

Readme

React Permission Guard

A flexible and easy-to-use permission system for React applications, with full support for Next.js 14 and React Server Components.

Features

  • 🚀 Built for React 18 and Next.js 14
  • 🔒 Type-safe permission checking
  • ⚡️ Component and page-level protection
  • 🎯 Single or multiple permission checks
  • 🔄 Automatic permission refresh
  • 📱 SSR compatible
  • 🎨 Customizable fallback components
  • 🌐 API-based permission management

Requirements

  • React 18 or higher
  • React DOM 18 or higher
  • Next.js 14 or higher (optional)
  • Node.js 16 or higher

Installation

npm install react-permission-guard
# or
yarn add react-permission-guard

Quick Start

1. Set up the Provider

The PermissionsProvider must be placed at the root level of your application, above any components that use permissions.

// app/providers.tsx - Create a client component for providers
'use client';

import { PermissionsProvider } from 'react-permission-guard';

const config = {
  getPermissionsEndpoint: '/api/permissions',  // Your permissions API endpoint
  checkSessionEndpoint: '/api/session',        // Optional: session check endpoint
  headers: {                                   // Optional: custom headers
    'Content-Type': 'application/json'
  }
};

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <PermissionsProvider config={config}>
      {children}
    </PermissionsProvider>
  );
}

// app/layout.tsx - Use the providers in your root layout
import { Providers } from './providers';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html>
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

2. Create API Routes (Next.js)

Your API endpoints should return permissions in one of these formats:

// Option 1: Object with permissions array
{
  permissions: ['admin', 'user', 'editor']
}

// Option 2: Direct array
['admin', 'user', 'editor']
// app/api/permissions/route.ts
export async function GET() {
  // Your permission fetching logic
  return Response.json({
    permissions: ['admin', 'user', 'editor']
  });
}

// app/api/session/route.ts (optional)
export async function GET() {
  const isLoggedIn = true; // Your session check logic
  return new Response(null, {
    status: isLoggedIn ? 200 : 401
  });
}

Usage

1. Protect Components

'use client';

import { PermissionGuard } from 'react-permission-guard';

// Single permission
function AdminPanel() {
  return (
    <PermissionGuard 
      permission="admin"
      fallback={<div>Access Denied</div>}
      loadingFallback={<div>Loading...</div>}
    >
      <div>Admin Content</div>
    </PermissionGuard>
  );
}

// Multiple permissions
function SuperAdminPanel() {
  return (
    <PermissionGuard 
      permissions={['admin', 'super_admin']}
      fallback={<div>Access Denied</div>}
      loadingFallback={<div>Loading...</div>}
    >
      <div>Super Admin Content</div>
    </PermissionGuard>
  );
}

2. Protect Entire Pages

'use client';

import { withPermission } from 'react-permission-guard';

// Your page component
function AdminDashboard() {
  return (
    <div>
      <h1>Admin Dashboard</h1>
      {/* Your dashboard content */}
    </div>
  );
}

// Custom fallback components (optional)
const CustomFallback = () => (
  <div className="flex min-h-screen items-center justify-center">
    <h1>Access Denied</h1>
  </div>
);

const CustomLoading = () => (
  <div className="flex min-h-screen items-center justify-center">
    <div>Loading...</div>
  </div>
);

// Protect the page
export default withPermission(AdminDashboard, {
  permission: 'admin',                    // Single permission
  // OR
  permissions: ['admin', 'super_admin'],  // Multiple permissions
  FallbackComponent: CustomFallback,      // Optional
  LoadingComponent: CustomLoading         // Optional
});

API Reference

PermissionsProvider

The root provider that manages permissions state. Must be placed at the root level of your application.

interface PermissionConfig {
  getPermissionsEndpoint: string;      // API endpoint to fetch permissions
  checkSessionEndpoint?: string;       // Optional: endpoint to check session
  headers?: HeadersInit;               // Optional: custom headers for API calls
}

PermissionGuard

Component-level protection.

interface PermissionGuardProps {
  children: ReactNode;
  permission?: string;                 // Single permission
  permissions?: string[];             // Multiple permissions
  fallback?: ReactNode;               // Component shown when unauthorized
  loadingFallback?: ReactNode;        // Component shown while loading
}

withPermission

Higher-order component for page-level protection.

interface WithPermissionOptions {
  permission?: string;                 // Single permission
  permissions?: string[];             // Multiple permissions
  FallbackComponent?: React.ComponentType;  // Custom unauthorized component
  LoadingComponent?: React.ComponentType;   // Custom loading component
}

Best Practices

  1. Always wrap your app with PermissionsProvider at the root level
  2. Create a separate client component for providers in Next.js
  3. Use PermissionGuard for component-level protection
  4. Use withPermission for page-level protection
  5. Implement proper API endpoints for permission management
  6. Handle loading states appropriately
  7. Provide meaningful fallback components
  8. Keep permission checks as close to the protected content as possible

Troubleshooting

Common Issues

  1. "usePermissions must be used within a PermissionsProvider"

    • Make sure your app is wrapped with PermissionsProvider
    • In Next.js, create a separate client component for providers
    • Check that the provider is above all components using permissions
  2. "Failed to fetch permissions"

    • Verify your API endpoints are correct and accessible
    • Check network tab for API responses
    • Ensure proper CORS configuration if needed
  3. Loading states not showing

    • Make sure to provide loadingFallback props
    • Check that your API endpoints have reasonable response times

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.