Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Modern Admin Dashboard Boilerplate: React 18, Vite, Ant Design, and Granular Role-Based Access Control

Tech May 19 1

Production-ready foundation for enterprise web applications leveraging a lightweight build pipeline and modular state management. The architecture prioritizes explicit configuration control over heavy scaffolding, enabling rapid iteration without SSR overhead.

Core Dependencies The stack centers on React 18 with functional components and hooks. State synchronization utilizes Redux Toolkit, while UI rendering relies on Ant Design 5.x. Styling is processed through Less preprocessors, and asynchronous HTTP operations are abstracted via Axios interceptors. Vite serves as the bundler, delivering optimized hot module replacement during development.

Build & Development Scripts Initialize the environment using package manager commands optimized for speed:

pnpm install
pnpm run dev
pnpm run build
pnpm run preview
pnpm run lint

The dev command launches the local server. build triggers the production compiler, generating statically optimized assets under dist. preview serves the compiled output locally for pre-deployment verification.

TypeScript Compilation Notes Strict type checking during production builds may flag interface mismatches in legacy utility functions. To resolve compilation errors without compromising broader type safety, explicitly widen parameter types in affected method signatures. Adjusting request payload definitions to accept Record<string, unknown> prevents compiler warnings while maintaining runtime compatibility.

Local Data Simulaiton Frontend testing integrates a mocking layer powered by Mock.js. This service intercepts HTTP requests matching specific URL patterns and returns predefined response structures. Disable this interceptor when deploying to staging or production environments to ensure direct API communication.

Mock Interceptor Implementation:

import Mock from 'mockjs';
import { generateAppRoutes } from './fixtures/routes';

// Intercept all /api/* requests
Mock.mock(/^\/api\//, (config: any) => {
  const payload = JSON.parse(config.body || '{}');
  return generateAppRoutes(payload);
});

Dynamic Routing Configuration Navigation trees are generated dynamically based on server-side role definitions. The backend should respond with a hierarchical array containing route metadata. Each node requires an identifier, display label, associated icon class, target path, parent reference, sort priority, and access conditions.

Expected Route Payload Structure:

interface NavNode {
  nodeId: string;
  label: string;
  iconCls: string;
  routePath: string;
  parentId?: string | null;
  sortOrder: number;
  visibilityMask: number;
}

const navigationData: NavNode[] = [
  {
    nodeId: 'nav-01',
    label: 'Dashboard',
    iconCls: 'pi-home',
    routePath: '/overview',
    parentId: null,
    sortOrder: 0,
    visibilityMask: 1
  },
  {
    nodeId: 'nav-02',
    label: 'Administration',
    iconCls: 'pi-settings',
    routePath: '/admin',
    parentId: null,
    sortOrder: 1,
    visibilityMask: 1
  },
  {
    nodeId: 'nav-03',
    label: 'User Directory',
    iconCls: 'pi-users',
    routePath: '/admin/users',
    parentId: 'nav-02',
    sortOrder: 0,
    visibilityMask: 1
  },
  {
    nodeId: 'nav-04',
    label: 'Role Definitions',
    iconCls: 'pi-shield-alt',
    routePath: '/admin/roles',
    parentId: 'nav-02',
    sortOrder: 1,
    visibilityMask: 1
  }
];

The frontend router consumes this structure to render conditional sidebar links and enforce path-based guards. Button-level restrictions evaluate the visibilityMask field against the authenticated user's permission set.

Session Persistence & Authentication Flow Client credentials are cached securely to support automatic re-authentiaction across page reloads. Passwords undergo a lightweight hashing routine before storage to prevent plaintext exposure in browser caches. Successful authentication triggers a state dispatch that updates the global store and navigates the client to the default landing route.

Login Handler Logic:

const handleAuthSubmit = async (): Promise<void> => {
  try {
    const formData = await validationSchema.validate();
    setLoadingState(true);

    const authResponse = await authenticateUser(formData.identifier, formData.credentials);

    if (authResponse.statusCode === 200 && authResponse.payload) {
      toast.success('Authentication successful');

      if (formData.rememberMe) {
        localStorage.setItem('persistentCreds', JSON.stringify({
          uid: formData.identifier,
          pwdHash: encryptValue(formData.credentials)
        }));
      } else {
        localStorage.removeItem('persistentCreds');
      }

      sessionStorage.setItem('activeSessionToken', compressPayload(authResponse.payload));
      await store.dispatch(updateUserProfile(authResponse.payload));
      router.replace('/dashboard');
    } else {
      toast.error(authResponse.message || 'Authentication failed');
      setLoadingState(false);
    }
  } catch (err) {
    console.warn('Validation or submission error:', err);
  }
};

Repository Acces Full source code, configuration files, and component implementations are available at: https://github.com/javaLuo/react-admin

Tags: ReactVite

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.