DEV Community

Cover image for React Hooks : How to use Authorization in react js with custom hook.
Rajiv Chaulagain
Rajiv Chaulagain

Posted on

React Hooks : How to use Authorization in react js with custom hook.

Here today I am gonna use custom hook and create a authorization for admin and other manager roles.

Lets start by creating a custom hook as useUserRole.js

import {useEffect} from 'react'
import { toast } from 'react-toastify'

import {useAuth} from './useAuth'

export const useUserRole = (allowedRoles) => {
  const {session} = useAuth()
  useEffect(() => {
    if (!allowedRoles.includes(session?.user?.role)) {
      localStorage.removeItem('session')
      window.location.reload()
      toast.error(`Unauthorized`)
    }
  }, [allowedRoles , session])
  return true
}
Enter fullscreen mode Exit fullscreen mode

here , we created an custom hook that takes allowedRoles and we are checking the allowedRoles with the role on our session during the login

here the condition is , if the allowedRoles is equal to the role in session then they are allowed to view the provided route else they will be redirect to login page.

Now we can specify the roles.

export const ROLE = {
  Admin: 'Admin',
  Manager: 'Manager',
  User: 'User'
}

Enter fullscreen mode Exit fullscreen mode

Now in any component like Blog.js


import React, { useState } from 'react'

import { useUserRole } from '../../../hooks/useUserRole'
import { ROLE } from '../../../_helpers/Role'

const Blog = () => {

//checking the role
  useUserRole([ROLE.Admin]);

  return ( 
        <>Blog page</>
  )
}

export default Blog
Enter fullscreen mode Exit fullscreen mode

Conclusion

Hence , the authorization is success and hence we can reuse the hook for the protected routes.

Top comments (0)