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-role-permission-pro

v1.0.0

Published

πŸš€ Complete Role & Permission Management System for React & Next.js with Beautiful UI, Auto Setup, and Advanced Features

Downloads

12

Readme

πŸš€ React Role Permission Pro

Complete Role & Permission Management System for React & Next.js with Beautiful UI, Auto Setup, and Advanced Features

npm version License: MIT Downloads

✨ Features

🎯 Core Features

  • βœ… Role Management - Create, edit, delete roles with Active/Inactive status
  • βœ… Permission Management - Organize permissions by modules
  • βœ… Role-Permission Assignment - Flexible permission assignment with presets
  • βœ… User-Role Assignment - Single or multiple roles per user
  • βœ… Super Admin - Bypass all permission checks
  • βœ… Route Protection - Next.js middleware for automatic route protection
  • βœ… Component Guards - React components for UI-level protection
  • βœ… Data Ownership - Scoped permissions (own, team, department, any)

🎨 UI Features

  • βœ… Beautiful Tailwind UI - Modern, responsive components
  • βœ… Dark Mode Support - Full dark mode compatibility
  • βœ… Dynamic Sidebar - Auto hide/show based on permissions
  • βœ… Permission Matrix - Visual permission assignment
  • βœ… Search & Filters - Fast role and permission filtering

πŸ” Advanced Features

  • βœ… Impersonation - Login as another user for debugging
  • βœ… Temporary Access - Time-based role assignment
  • βœ… Audit Logging - Track all role/permission changes
  • βœ… Activity History - Monitor user actions
  • βœ… Soft Delete - Safe role deletion with recovery
  • βœ… Permission Presets - Quick role setup with templates
  • βœ… Frontend Caching - Fast permission checks with encryption
  • βœ… API Security - Backend guards for API routes

πŸ“¦ Installation

npm install react-role-permission-pro
# or
yarn add react-role-permission-pro
# or
pnpm add react-role-permission-pro

πŸš€ Quick Start

1. Initialize the Package

npx role-permission init

This will:

  • βœ… Detect your project type (Next.js/React)
  • βœ… Copy necessary configuration files
  • βœ… Setup database tables and migrations
  • βœ… Seed default roles and permissions
  • βœ… Create example routes

2. Configure Environment Variables

# Database
DATABASE_URL="postgresql://user:password@localhost:5432/mydb"

# JWT Secret
JWT_SECRET=your-super-secret-jwt-key

# App Configuration
NEXT_PUBLIC_APP_URL=http://localhost:3000

3. Wrap Your App with Provider

// app/layout.js or _app.js
import { RolePermissionProvider } from 'react-role-permission-pro';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <RolePermissionProvider
          config={{
            apiBaseUrl: '/api',
            cacheEnabled: true
          }}
        >
          {children}
        </RolePermissionProvider>
      </body>
    </html>
  );
}

4. Protect Your Routes

// middleware.js
import { middleware } from 'react-role-permission-pro/middleware';

export { middleware };

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico|public).*)']
};

πŸ“– Usage Examples

Component Level Protection

import { PermissionGate, Can, PermissionButton } from 'react-role-permission-pro';

function MyComponent() {
  return (
    <div>
      {/* Method 1: Using PermissionGate */}
      <PermissionGate permission="product.create">
        <button>Create Product</button>
      </PermissionGate>

      {/* Method 2: Using Can */}
      <Can permission="product.update">
        <button>Edit Product</button>
      </Can>

      {/* Method 3: Using PermissionButton */}
      <PermissionButton
        permission="product.delete"
        onClick={handleDelete}
        variant="danger"
      >
        Delete Product
      </PermissionButton>

      {/* Multiple Permissions (require all) */}
      <Can permission={['product.read', 'product.update']} requireAll>
        <button>Advanced Edit</button>
      </Can>

      {/* Multiple Permissions (require any) */}
      <Can permission={['admin', 'manager']}>
        <button>Management Panel</button>
      </Can>
    </div>
  );
}

Hook-based Permission Checks

import { usePermission, useRole, useAuth } from 'react-role-permission-pro';

function ProductCard({ product }) {
  const canEdit = usePermission('product.update');
  const canDelete = usePermission('product.delete');
  const { hasRole } = useRole();
  const { user } = useAuth();

  const isAdmin = hasRole('admin');

  return (
    <div>
      <h3>{product.name}</h3>
      {canEdit && <button>Edit</button>}
      {canDelete && <button>Delete</button>}
      {isAdmin && <button>Advanced Settings</button>}
    </div>
  );
}

Data Ownership Checks

import { useCanAccessResource } from 'react-role-permission-pro';

function ProductEditPage({ product }) {
  // Checks both permission AND ownership
  const canEdit = useCanAccessResource('product.update', product);

  if (!canEdit) {
    return <div>You can only edit your own products</div>;
  }

  return <ProductForm product={product} />;
}

API Route Protection (Next.js)

// app/api/products/route.js
import { withPermission, withOwnership } from 'react-role-permission-pro/middleware';

// Simple permission check
export const GET = withPermission('product.read', async (request, user) => {
  const products = await db.product.findMany();
  return NextResponse.json({ data: products });
});

// With ownership check
export const PUT = withOwnership(
  'product.update',
  async (id) => await db.product.findUnique({ where: { id } }),
  async (request, user, context, product) => {
    const body = await request.json();
    const updated = await db.product.update({
      where: { id: product.id },
      data: body
    });
    return NextResponse.json({ data: updated });
  }
);

Beautiful UI Components

import { 
  RoleList, 
  PermissionMatrix, 
  DynamicSidebar,
  AuditLogViewer
} from 'react-role-permission-pro/components';

function AdminPage() {
  return (
    <div className="container mx-auto p-6">
      {/* Roles Management */}
      <RoleList
        onEdit={handleRoleEdit}
        onDelete={handleRoleDelete}
        roleManager={roleManager}
      />

      {/* Permission Matrix */}
      <PermissionMatrix
        roleId={selectedRoleId}
        onUpdate={handlePermissionUpdate}
      />

      {/* Dynamic Sidebar */}
      <DynamicSidebar
        items={sidebarItems}
        collapsible
      />

      {/* Audit Log Viewer */}
      <AuditLogViewer
        filters={{ entityType: 'role' }}
        pageSize={20}
      />
    </div>
  );
}

Impersonation (Super Admin Feature)

import { useAuth } from 'react-role-permission-pro';

function UserManagement() {
  const { impersonate, stopImpersonation, isImpersonating } = useAuth();

  const handleImpersonate = async (userId) => {
    try {
      await impersonate(userId);
      // Now logged in as that user
    } catch (error) {
      console.error('Impersonation failed:', error);
    }
  };

  return (
    <div>
      {isImpersonating() && (
        <div className="bg-yellow-100 p-4">
          <p>You are impersonating another user</p>
          <button onClick={stopImpersonation}>
            Stop Impersonation
          </button>
        </div>
      )}

      {/* User list with impersonate button */}
    </div>
  );
}

🎯 Permission Scopes

The package supports different permission scopes for data ownership:

| Scope | Description | Use Case | |-------|-------------|----------| | own | User can only access their own resources | Sellers editing their products | | team | User can access team resources | Team members sharing projects | | department | User can access department resources | Department managers | | any | User can access all resources | Admins and super users |

Setting Permission Scopes

// When creating permissions
const permission = {
  slug: 'product.update',
  scope: 'own', // Default
  // User with this permission can only update their own products
};

// Admin with 'any' scope
const adminPermission = {
  slug: 'product.update',
  scope: 'any',
  // Can update any product
};

πŸ—‚οΈ Database Schema

The package automatically creates these tables:

  • roles - Role definitions
  • permissions - Permission definitions
  • role_permissions - Role-Permission mapping
  • user_roles - User-Role assignment
  • permission_groups - Permission presets
  • audit_logs - Change tracking
  • activity_history - User activity tracking

Supports: Prisma, Sequelize, TypeORM, Mongoose

🎨 Styling & Customization

Tailwind Configuration

// tailwind.config.js
module.exports = {
  content: [
    './node_modules/react-role-permission-pro/**/*.{js,jsx}'
  ],
  // Your config...
};

Theme Customization

<RolePermissionProvider
  config={{
    theme: {
      colors: {
        primary: '#3B82F6',
        danger: '#EF4444',
        success: '#10B981'
      }
    }
  }}
>
  {children}
</RolePermissionProvider>

πŸ”§ CLI Commands

# Initialize package in your project
npx role-permission init

# Setup database
npx role-permission setup-db

# Generate TypeScript types
npx role-permission generate-types

# Sync routes with permissions
npx role-permission sync-routes

# Show help
npx role-permission help

πŸ“Š Pre-built Permission Presets

import { PermissionManager } from 'react-role-permission-pro';

const permissionManager = new PermissionManager();

// Apply preset to a role
await permissionManager.applyPreset(roleId, 'editor');

// Available presets:
// - admin: Full access
// - editor: Content management
// - support: Customer support
// - viewer: Read-only access

πŸ› Debugging & Logging

<RolePermissionProvider
  config={{
    debug: true, // Enable console logs
    logLevel: 'verbose' // 'verbose' | 'info' | 'error'
  }}
>
  {children}
</RolePermissionProvider>

πŸ“ TypeScript Support

Full TypeScript definitions included:

import type { 
  Role, 
  Permission, 
  User,
  PermissionScope 
} from 'react-role-permission-pro';

const role: Role = {
  id: '123',
  name: 'Admin',
  slug: 'admin',
  isActive: true,
  isSuperAdmin: false
};

🀝 Contributing

Contributions are welcome! Please read our Contributing Guide.

πŸ“„ License

MIT Β© SNDP Bag

πŸ™ Support

🌟 Show Your Support

Give a ⭐️ if this project helped you!


Made with ❀️ by SNDP Bag