Avoid Using URL as Source of Truth in React Apps

I stopped trusting the URL as the source of truth in my React app While building my latest expense tracker, I noticed a common pattern when working with dynamic routes. ➤ The Scenario: I’m using React Router for navigation and Context API for authentication. ⤷ My dashboard route was defined as: /dashboard/:username ➤ The Problem: Initially, I was reading the username directly from useParams(). It was only for UX purposes (I wanted to display the username in the URL). ⤷ But then I realized: → If a logged-in user manually changes the URL (e.g., /dashboard/ali), the UI state can become inconsistent with the authenticated user. → Even though the backend enforces authorization, the frontend should not treat the URL as the source of truth for user identity. ➤ The Fix: I made the Auth Context the single source of truth and added a guard to keep the UI in sync: ------------------------------------------------------- Dasboard.jsx useEffect(() => { if (user && username !== user) { navigate(`/dashboard/${user}`, { replace: true }); } }, [username, user, navigate]); ------------------------------------------------------- ➤ Key Takeaway: → The URL is user-controlled input → Auth state should always drive UI behavior → Keep your frontend consistent with the authentication layer Question I should ask experts: Is using URL params for display purposes (like usernames in routes) a good practice, or does it add unnecessary complexity in authenticated apps? #ReactJS #WebDevelopment #JavaScript #Frontend #SoftwareEngineering

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories