Hi Guys!Hoping things are going not too bad for you to startover :)Let's step into the another mode ,where you'll understand the interlinking of server and client is done just by setting few things, which always tries to confuse us.Infact I was confused aswell😅
In the world of perfectionism !Everybody wants to be perfect in everything ,but don't have enough time to practice.Which is what I'm trying 2 do here!Let's start.
To work on the project locally set things like
1.Setup proxy for client in package.json
"proxy": "http://localhost:5000"
2.Use cors for handling the issues like connecting frontend and backend as they run on different ports.
As the server is running on suppose 3000,and want to connect to client of 5000 CORS() helps in achieving this by adding just.
app.use(cors());
3.In frontend to access the data from the database or to add anything to it, we use axios.Axios are the promise based HTTP requests which helps to request the backend from frontend.
Unlike, fetch axios hepls to retrieve the data by automatically converting json response to js objects,which provides easier codeflow.
axios.get("http://localhost:3000/data").then(res => console.log(res.data));
Set a base URL once instead of repeating it in every request.
const api = axios.create({
baseURL: "http://localhost:3000",
timeout: 5000
});
api.get("/users").then(res => console.log(res.data));
adding in login component.
import API from "../api"; // Import Axios instance
const handleLogin = async (e) => {
e.preventDefault();
try {
const res = await API.post("/auth/login", { email, password });
localStorage.setItem("token", res.data.token);
console.log("Login successful:", res.data);
} catch (err) {
console.error("Login failed:", err.response.data);
}
};
the tokens from above are set to handle user Authentication using jsonwebtoken in backend.
for this, create a utils/auth.js file in backend directory and add this logic to generate the token for particular login user.utils/auth.js
const jwt = require('jsonwebtoken');
module.exports = function(req, res, next) {
const token = req.header('auth-token');
if (!token) return res.status(401).send('Access denied');
try {
const verified = jwt.verify(token, process.env.JWT_SECRET);
req.user = verified;
next();
} catch (err) {
res.status(400).send('Invalid token');
}
};
this provides secure authentication between frontend and backend and let's user access protected routes without repititive logins, until the token expires.
that file is described in controllers part if using ,or in the route handlers where the controller part is handled inorder to request or acces based on the requested object.
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../model/User');
const router = express.Router();
router.post('/login', async (req, res) => {
const { username, password } = req.body;
const user = await User.findOne({ username });
if (!user) return res.status(400).send('Invalid credentials');
const validPassword = await bcrypt.compare(password, user.password);
if (!validPassword) return res.status(400).send('Invalid credentials');
const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET);//creates the token based on the userid with secret key defined in .env file
res.header('auth-token', token).send(token);
});
and this is passed to the protected route to get accessed by the specified user.
Example:
Consider instagram - When you login ur posts, likes ,and ur activity are private to u right .When u login to different user ur activity is different from previous one.This is how ,authentication works with handling the protected routes.As, teh protected routes is "ur activity" for ur user respective id which is unique,FOr that jsonwebtoken is initialized.And if you logout the token is removed if you add in logout component
const handleLogout = () => {
localStorage.removeItem("token");
window.location.href = "/login"; // Redirect to login page
};
protected routes format
const express = require('express');
const verifyToken = require('../utils/auth');
const router = express.Router();
router.get('/', verifyToken, (req, res) => {
res.send('This is a protected post');
});
module.exports = router;
To check the localstorage inspect ur application and click on application and see in the sidebar localstorage,cookies etc.
This is a little intro or revision kind of thing.Prefer to reply👍 on this blog and make me create more useful content.Happy developing!😀
Top comments (0)