Skip to content

Instantly share code, notes, and snippets.

@OmarKhattab
Last active July 21, 2020 01:00
Show Gist options
  • Save OmarKhattab/5f929205eb7bce80534a5741d24525ab to your computer and use it in GitHub Desktop.
Save OmarKhattab/5f929205eb7bce80534a5741d24525ab to your computer and use it in GitHub Desktop.
Private Route React Router Dom
import React, { useEffect } from 'react';
import { Route, useHistory } from 'react-router-dom';
import jwt from 'jsonwebtoken';
const PrivateRoute = ({ children, ...rest }) => {
const history = useHistory();
useEffect(() => {
const onMount = async () => { // create an async function
let localStorageUser = localStorage.getItem('user'); // check if user exists in localstorage
let isValid = true; // is the json web token still valid?
if (localStorageUser) {
localStorageUser = JSON.parse(localStorageUser); // user was logged in so parse the stringified json
const decodedJWT = await jwt.decode(localStorageUser.jwt);
const dateNow = new Date(); // get the current date
if (decodedJWT.exp < dateNow.getTime() / 1000) { // check if token expired
isValid = false; // if expired its invalid
}
}
if (!isValid) history.push('/login'); // if its not valid redirect to login
};
onMount(); // call function inside use effect hook
}, []);
return <Route {...rest}>{children}</Route>; // pass down any router props and render the children components
};
export default PrivateRoute;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment