Let's Take It Quick!
After you start your project, make sure to install all dependencies:
npm install axios react-router-dom
This way, you already have all the dependencies to create authentication for your project!
Login Component
The second step is creating your login component, so you can input the login information.
You need to import useState
to manage form input state and useHistory
to redirect users after successful login.
import React, { useState } from 'react';
import axios from 'axios';
import { useHistory } from 'react-router-dom';
const Login = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const history = useHistory();
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post('/api/login', { email, password });
if (response.data.success) {
localStorage.setItem('token', response.data.token);
history.push('/dashboard');
} else {
alert('Invalid credentials');
}
} catch (error) {
console.error('Login error:', error);
}
};
return (
<form onSubmit={handleSubmit}>
<h2>Login</h2>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
<button type="submit">Login</button>
</form>
);
};
export default Login;
Setting Your Routes
In src/App.js
, set up the routes. Import BrowserRouter
, Route
, and Switch
from react-router-dom
to define the routes. This sets up two routes: one for the login page and one for the dashboard.
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Login from './Login';
import Dashboard from './Dashboard';
function App() {
return (
<Router>
<Switch>
<Route path="/" exact component={Login} />
<Route path="/dashboard" component={Dashboard} />
</Switch>
</Router>
);
}
export default App;
Creating Private Routes
Create the PrivateRoute.js
component to protect your routes. This component will check if the user is authenticated before granting access.
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
const PrivateRoute = ({ component: Component, ...rest }) => {
const isAuthenticated = !!localStorage.getItem('token');
return (
<Route
{...rest}
render={(props) =>
isAuthenticated ? <Component {...props} /> : <Redirect to="/" />
}
/>
);
};
export default PrivateRoute;
Update your routing in App.js
to use the PrivateRoute
for the dashboard.
<PrivateRoute path="/dashboard" component={Dashboard} />
Backend API
This code will be validating a user's email and password and returning a JSON Web Token (JWT).
const express = require('express');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.post('/api/login', (req, res) => {
const { email, password } = req.body;
if (email === 'test@example.com' && password === 'password123') {
const token = jwt.sign({ email }, 'your_jwt_secret', { expiresIn: '1h' });
return res.json({ success: true, token });
}
res.json({ success: false, message: 'Invalid credentials' });
});
app.listen(5000, () => {
console.log('Server is running on port 5000');
});
Tips
After a successful login, store the JWT token
in localStorage
. To keep it secure:
- Do not store sensitive information in the token.
- Use HTTPS to encrypt data in transit.
- Implement token expiration and refresh mechanisms.
Thank you.
Please Follow: Frontend Ai