Folder Structure
package.json:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.3",
"web-vitals": "^2.1.4"
}
Example: Create the required files as seen on the folder structure and add the following codes.
//App.js
import {
BrowserRouter as Router,
Routes, Route
} from 'react-router-dom'
import Home from './Home'
import Login from './Login'
import PrivateRoutes from './utils/PrivateRoutes'
function App() {
return (
<div className="App">
<Router>
<Routes>
<Route element={<PrivateRoutes />}>
<Route element={<Home />}
path="/" exact />
</Route>
<Route element={<Login />}
path="/login" />
</Routes>
</Router>
</div>
);
}
export default App;
//utils/PrivateRoutes.js
import {
Outlet,
Navigate
} from 'react-router-dom'
const PrivateRoutes = () => {
let auth = { 'token': false }
return (
auth.token ?
<Outlet /> :
<Navigate to="/login" />
)
}
export default PrivateRoutes
//Home.js
import React from 'react'
const Home = () => {
return (
<h1>Home</h1>
)
}
export default Home
//Login.js
import React from 'react'
const Login = () => {
return (
<h1>Login</h1>
)
}
export default Login
To start the applicrion run the following command.
npm start
Output:
What are Protected Routes in React JS ?
In web development, security is critical when building React applications, especially those handling sensitive data or functionalities, it’s crucial to restrict access to certain parts of the application to authorized users only. This is where protected routes come into play.
In this article, we will learn in detail about Protected Routes in React Router.
Table of Content
- What are Protected Routes ?
- Authentication and Authorization
- Features of Protected Routes
- Steps to Implement Protected Routes
- Folder Structure
- Benefits of Protected Routes