Hi i am working check jwt expired and logout or reflesh token. i try a lot of thing but i didn't solve it. I use react for frontend and node for backend.
Frontend (react.js) AuthContent.js
import axios from "axios";
import { createContext, useEffect, useState } from "react";
import jwt_decode from "jwt-decode";
import { withRouter } from "../components/with-router";
export const AuthContext = createContext();
export const AuthContexProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(
JSON.parse(localStorage.getItem("user")) || null
);
const login = async (inputs) => {
const res = await axios.post("/auth/login", inputs);
setCurrentUser(res.data);
console.log(res.data)
};
const logout = async (inputs) => {
await axios.post("/auth/logout");
setCurrentUser(null);
};
useEffect(() => {
localStorage.setItem("user", JSON.stringify(currentUser));
}, [currentUser]);
return (
<AuthContext.Provider value={{ currentUser, login, logout }}>
{children}
</AuthContext.Provider>
);
};
backend (node.js) auth.js
`
import {db} from "../db.js"
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
export const register = (req,res) => {
const q = "SELECT * FROM users WHERE email = ? "
db.query(q, [req.body.email], (err, data) => {
if (err) return res.status(500).json(err);
if (data.length) return res.status(409).json("User already exists!");
//Hash the password and create a user
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(req.body.password, salt);
const q = "INSERT INTO users(`firstname`,`lastname`,`email`,`password`) VALUES (?)";
const values = [req.body.firstName, req.body.lastName, req.body.email, hash];
db.query(q, [values], (err, data) => {
if (err) return res.status(500).json(err);
return res.status(200).json("User has been created.");
});
});
};
export const login = (req,res) => {
//CHECK USER
const q = "SELECT * FROM users WHERE email = ?";
db.query(q, [req.body.email], (err, data) => {
if (err) return res.status(500).json(err);
if (data.length === 0) return res.status(404).json("User not found!");
//Check password
const isPasswordCorrect = bcrypt.compareSync(
req.body.password,
data[0].password
);
if (!isPasswordCorrect)
return res.status(400).json("Wrong username or password!");
const token = jwt.sign({ id: data[0].id, expiresIn: '24h' }, "jwtkey");
const { password, ...other } = data[0];
res
.cookie("access_token", token, {
httpOnly: true,
})
.status(200)
.json(other);
});
};
export const logout = (req, res) => {
res.clearCookie("access_token",{
sameSite:"none",
secure:true
}).status(200).json("User has been logged out.")
};
I try reach access_token in frontend but always return null. i try axios interceptors but i cant solve it.