Introduction:
JSON Web Tokens (JWT) are a popular method for authentication in web applications. One critical aspect of using JWT is verifying their expiry to maintain application security. In this tutorial, we'll walk through how to verify JWT token expiry in a React/Next.js app, ensuring that our application remains secure.
Prerequisites:
Before we begin, ensure you have the following:
- Node.js + Express.js and JSON web token for the backend.
- React and Next.js for the frontend.
Setting up Token Expiry in the Node/Express Backend:
In our Node/Express backend, let's build a simple login controller with expiration time for our token. Here's an example code snippet:
const login = async (req, res) => {
try {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(404).send({ message: 'User not found' });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(404).send({ message: 'Incorrect password' });
}
const token = jwt.sign({ _id: user._id }, process.env.SECRET, {
expiresIn: 86400, // expires in 24 hours
});
res.status(200).send({ token, user });
} catch (error) {
res.status(404).send({ message: error.message });
}
};
Verifying Token Expiry in the React/Next.js Frontend:
In our React/Next.js frontend, let's use the jwt-decode library to check token expiry. Here's how you can do it:
Firstly, we need to install the library:
npm install jwt-decode
or yarn add jwt-decode
Then, let's import and use it, like this:
import jwtDecode from 'jwt-decode';
const isTokenExpired = (token) => {
if (!token) return true;
try {
const decodedToken = jwtDecode(token);
const currentTime = Date.now() / 1000;
return decodedToken.exp < currentTime;
} catch (error) {
console.error('Error decoding token:', error);
return true;
}
};
Handling Expired Tokens:
When a token is expired, we need to remove it from local storage and redirect the user to the login page. Like so:
useEffect(() => {
if (localStorage.getItem('token')) {
const token = localStorage.getItem('token');
if (isTokenExpired(token)) {
localStorage.removeItem('token');
router.push('/login');
} else {
setUser(JSON.parse(localStorage.getItem('user')));
}
} else {
router.push('/login');
}
}, [router]);
Security Considerations:
It's crucial to handle JWT tokens securely. Consider using secure storage mechanisms and validating tokens on the server side to prevent security vulnerabilities.
Conclusion:
By verifying JWT token expiry in our React/Next.js app, we can ensure that the application remains secure against unauthorized access. Implementing token expiry checks is a critical step in maintaining the integrity of the authentication system.
Additional Resources:
Top comments (0)