Back to Snippets

React Higher Order Component For Authentication And Authorization In Large Scale Applications

JavaScript Security May 7, 2026

This React higher order component handles authentication and authorization by checking user credentials before rendering the wrapped component. It utilizes React hooks for state management and error handling, making it suitable for large-scale applications where authentication logic needs to be reused. The component checks for user authentication and authorization based on predefined roles. It is particularly useful in complex applications with multiple authorization levels.

Snippet Stats

Lines 43
Characters 1,247
Read 2 mins
javascript • 43 lines
import React, { useState, useEffect, useContext } from 'react';
import { AuthContext } from './AuthContext';

const withAuth = (WrappedComponent, allowedRoles) => {
   const AuthComponent = () => {
       const { user, isAuthenticated } = useContext(AuthContext);
       const [isAuthorized, setIsAuthorized] = useState(false);
       const [error, setError] = useState(null);

       useEffect(() => {
           const checkAuthorization = async () => {
               try {
                   if (isAuthenticated && user.roles.some(role => allowedRoles.includes(role))) {
                       setIsAuthorized(true);
                   } else {
                       setIsAuthorized(false);
                   }
               } catch (error) {
                   setError(error.message);
               }
           };
           checkAuthorization();
       }, [isAuthenticated, user?.roles, allowedRoles]);

       if (!isAuthenticated) {
           return <div>You are not authenticated.</div>;
       }

       if (!isAuthorized) {
           return <div>You are not authorized to access this resource.</div>;
       }

       if (error) {
           return <div>Error: {error}</div>;
       }

       return <WrappedComponent />;
   };

   return AuthComponent;
};

export default withAuth;

Found an issue with this snippet? Help us improve by reporting it. Report it →

Related Snippets

View all
JavaScript
This React higher-order component handles authentication and authorization by wrapping the provided component with authentication checks, ensuring onl...

React Higher Order Component For Role Based Authentication And Authorization

PHP
This snippet provides a custom WordPress plugin that utilizes hooks to modify the user registration process, allowing for additional validation and cu...

WordPress Custom Plugin Hooks For User Registration

PHP
Complete form handling pattern — nonce verification, input sanitization, validation with error messages, and secure redirect. Production-ready.

Sanitize and Validate Form Input