How to Properly Implement Role-Based Authorization in React Using Context API and React Query?

I am trying to work on a React application where I want to implement role-based authorization.

My goal is to fetch user roles from an API and store them in context so they can be accessed throughout the application. I am using the Context API and React Query for state management and data fetching.

I am having trouble finding information about how to do so effectively as most information about it seems to be using old formats. Or is just about Authentication rather than Authorization.

I saw some people recommeding to use JWT-decoder on React but I dont know how safe it is to decode your token In the Client Side… nor how to properly implement it.

What I was trying to do was fetch the role straight from the server and save the data in a context and then just if check all protected routes for the correct roles (or especialidades for this proyect)

This is the context I was trying to make work:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const AuthContext = createContext<string[] | undefined>(undefined);
export const AuthContextProvider = ({children} :{children:ReactNode})=>{
const {data:roles} = useQuery({
queryFn: ()=> fetchRole(),
queryKey: ["roles"],
})
const userRoles = roles || [];
return(
<AuthContext.Provider value={userRoles}>
{children}
</AuthContext.Provider>
)
}
export const useAuthContext = ()=>{
const context = useContext(AuthContext);
return context;
}
</code>
<code>const AuthContext = createContext<string[] | undefined>(undefined); export const AuthContextProvider = ({children} :{children:ReactNode})=>{ const {data:roles} = useQuery({ queryFn: ()=> fetchRole(), queryKey: ["roles"], }) const userRoles = roles || []; return( <AuthContext.Provider value={userRoles}> {children} </AuthContext.Provider> ) } export const useAuthContext = ()=>{ const context = useContext(AuthContext); return context; } </code>
const AuthContext = createContext<string[] | undefined>(undefined);

export const AuthContextProvider = ({children} :{children:ReactNode})=>{
        const {data:roles} = useQuery({
            queryFn: ()=> fetchRole(),
            queryKey: ["roles"],
        })
        const userRoles = roles || [];

        return(
            <AuthContext.Provider value={userRoles}>
                {children}
            </AuthContext.Provider>
        )
}

export const useAuthContext = ()=>{
    const context = useContext(AuthContext);
    return context;
} 

// The fetch function

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export const fetchRole = async ():Promise<string[]>=>{
const response = await fetch("http://localhost:3000/api/auth/check-role",{
credentials: "include",
});
if (!response.ok) {
throw new Error("Something went wrong...");
}
return response.json();
}
</code>
<code>export const fetchRole = async ():Promise<string[]>=>{ const response = await fetch("http://localhost:3000/api/auth/check-role",{ credentials: "include", }); if (!response.ok) { throw new Error("Something went wrong..."); } return response.json(); } </code>
export const fetchRole = async ():Promise<string[]>=>{
    const response = await fetch("http://localhost:3000/api/auth/check-role",{
        credentials: "include",
    });
    if (!response.ok) {
        throw new Error("Something went wrong...");
    }
    return response.json();
}

//The backend Route, MiddleWare and Response

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>authRoutes.get('/check-role',verifyToken,async ( req:Request, res:Response)=>{
console.log(req.medicoInfo.especialidad)
res.status(200).json({medicoRoles: req.medicoInfo.especialidad});
})
const verifyToken = (req: Request, res: Response, next: NextFunction)=>{
const token = req.cookies["auth_cookie"];
console.log(token);
if(!token){
return res.status(401).json({message: "Unauthorized"});
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET as string);
req.medicoInfo = (decoded as JwtPayload).medicoInfo;
next();
} catch (error) {
return res.status(401).json({message: "Unauthorized"});
}
}
</code>
<code>authRoutes.get('/check-role',verifyToken,async ( req:Request, res:Response)=>{ console.log(req.medicoInfo.especialidad) res.status(200).json({medicoRoles: req.medicoInfo.especialidad}); }) const verifyToken = (req: Request, res: Response, next: NextFunction)=>{ const token = req.cookies["auth_cookie"]; console.log(token); if(!token){ return res.status(401).json({message: "Unauthorized"}); } try { const decoded = jwt.verify(token, process.env.JWT_SECRET as string); req.medicoInfo = (decoded as JwtPayload).medicoInfo; next(); } catch (error) { return res.status(401).json({message: "Unauthorized"}); } } </code>
authRoutes.get('/check-role',verifyToken,async ( req:Request, res:Response)=>{
    console.log(req.medicoInfo.especialidad)
    res.status(200).json({medicoRoles: req.medicoInfo.especialidad});
})


const verifyToken = (req: Request, res: Response, next: NextFunction)=>{
    const token = req.cookies["auth_cookie"];
    console.log(token);
    if(!token){
        return res.status(401).json({message: "Unauthorized"});
    }
    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET as string);
        req.medicoInfo = (decoded as JwtPayload).medicoInfo;
        next();
    } catch (error) {
        return res.status(401).json({message: "Unauthorized"});
    }
}

//MiddleWare

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const verifyToken = (req: Request, res: Response, next: NextFunction)=>{
const token = req.cookies["auth_cookie"];
console.log(token);
if(!token){
return res.status(401).json({message: "Unauthorized"});
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET as string);
req.medicoInfo = (decoded as JwtPayload).medicoInfo;
next();
} catch (error) {
return res.status(401).json({message: "Unauthorized"});
}
}
</code>
<code>const verifyToken = (req: Request, res: Response, next: NextFunction)=>{ const token = req.cookies["auth_cookie"]; console.log(token); if(!token){ return res.status(401).json({message: "Unauthorized"}); } try { const decoded = jwt.verify(token, process.env.JWT_SECRET as string); req.medicoInfo = (decoded as JwtPayload).medicoInfo; next(); } catch (error) { return res.status(401).json({message: "Unauthorized"}); } } </code>
const verifyToken = (req: Request, res: Response, next: NextFunction)=>{
    const token = req.cookies["auth_cookie"];
    console.log(token);
    if(!token){
        return res.status(401).json({message: "Unauthorized"});
    }
    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET as string);
        req.medicoInfo = (decoded as JwtPayload).medicoInfo;
        next();
    } catch (error) {
        return res.status(401).json({message: "Unauthorized"});
    }
}

The data is being fetched but How can I implement it.. How can I make it so this data protects my Routes, and help the users navigate safely through an app.

Should I change my Context? I saw somewhere that I should just both send the token and the roles when Sign In but I am beyond lost how could I use them. I just don’t know whats the next step after fetching and just putting them in a context or if it even is the best option.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật