How can I logout user when the JWT accessToken expires?
Right now I am using withRouter
as a Higher order component(HOC) to check for route change, but it only works when the user clicks the back button of browser.
I want to check for route changes at every route change not just back button. for example, when the user clicks back to home link, I want to check if the token has expired and then remove token from local Storage.
AuthVerify.js
import React, { useEffect } from "react";
import { withRouter } from "react-router-dom";
const parseJwt = (token) => {
try {
return JSON.parse(atob(token.split(".")[1]));
} catch (e) {
return null;
}
};
const AuthVerify = (props) => {
console.log(props);
useEffect(() => {
props.history.listen(() => {
const token = localStorage.getItem("accessToken");
if (token) {
const decodedJWT = parseJwt(token);
if (decodedJWT.exp * 1000 < Date.now()) {
console.log("expired");
props.logOut();
} else {
}
}
});
}, []);
return <div></div>;
};
export default withRouter(AuthVerify);
Part of App.js
import { Fragment } from "react";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import AuthVerify from "../src/utils/AuthVerify";
import "./App.css";
import Home from "./pages/Home";
import Signup from "../src/pages/Signup";
import Login from "../src/pages/Login";
import Test from "./pages/Test";
const logOut = () => {
localStorage.removeItem("accessToken");
localStorage.removeItem("refreshToken");
};
function App() {
return (
<Fragment>
<div className="App">
<BrowserRouter>
<Switch>
<Route exact path="/" component={Home} />
<PrivateRoute exact path="/test" component={Test} />
<Route exact path="/register" component={Signup} />
<Route exact path="/login" component={Login} />
</Switch>
</BrowserRouter>
</div>
<AuthVerify logOut={logOut} />
</Fragment>
);
}
export default App;