🔒

Creating Protected Routes with React Router 6

Jul 9, 2024

Creating Protected Routes with React Router 6

Introduction

  • Topic: Creating protected routes in React using React Router 6
  • Context: Migration from React Router 5 to React Router 6
  • Goal: Protect routes from unauthenticated users or users without permissions

Initial Application Setup

  • Created a basic React application
  • Components: Home, Login, Products
  • Demo purposes: Simplified components

Previous Method (React Router 5)

  • Private Route Component: Extending Route component
  • Authentication Check: Used JSON Web Token (JWT) or Redux Context API
  • Render Logic: Redirect to login if unauthenticated
  • Issue: React Router 6 changes causing conflicts

Key Changes in React Router 6

  • Redirect Component: Replaced with Navigate
  • Switch Component: Replaced with Routes
  • Direct Children Requirement: Direct children of Routes must be Route components

Steps to Update to React Router 6

  1. Import Routes
    • Wrap application components inside Routes
  2. Change Redirect to Navigate
    • Update all instances of Redirect to Navigate
  3. Use of Outlet
    • Use Outlet to nest routes
    • Allows extending routes logic

Example Update

  • Private Route Component Update:
    • Use Auth Token to check authentication
    • Use Outlet to render nested routes if authenticated
    • Use Navigate to redirect if unauthenticated
    • Change name to Private Routes
    • Simplify route declaration
  • App.js Update:
    • Import Private Routes
    • Use element instead of component
    • Nest routes inside Private Routes

Final Setup

  • Routes nested correctly to protect the required paths
  • Verification of functionality by manual toggling of auth status

Conclusion

  • Showcased protected routes setup using React Router 6
  • Suggestions and Feedback requested
  • Additional resources: Linked article in video description