Access Token V/S Refresh Token
Nikhil Kumar
2 min read
JWT
JWT Stands for Json Web Token, it used for to set the cookies basically performing the CRUD (Create, Read, Update, Delete) operations.
Difference between Access & Refresh Token
Basically Access token and refresh token both are set in the cookies but Refresh token is used for the refresh the Access token.
Access token is temporary credentials to protect the resources but Refresh token is used to obtain the new Access token if current one is expired.
While the Access Token is keeping or holding the more details as a payload but Refresh Token
is holding the less and less details eg. userId .
userSchema.methods.generateAccessToken = function () {
return jwt.sign(
{
_id: this._id,
email: this.email,
username: this.username,
fullName: this.fullName,
},
process.env.ACCESS_TOKEN_SECRET,
{
expiresIn: process.env.ACCESS_TOKEN_EXPIRY,
}
);
};
userSchema.methods.generateRefreshToken = function () {
return jwt.sign(
{
_id: this._id,
},
process.env.REFRESH_TOKEN_SECRET,
{
expiresIn: process.env.REFRESH_TOKEN_EXPIRY,
}
);
};
Refresh the Access token
const refreshAccessToken = asyncHandler(async (req, res)=> {
const incomingRefreshToken = req.cookies.refreshToken || req.body.refreshToken;
if(!incomingRefreshToken){
throw new ApiError(401, "Unauthorized request") // Error Handing
}
try {
const decodedToken = jwt.verify(incomingRefreshToken, process.env.REFRESH_TOKEN_SECRET);
const user = await User.findById(decodedToken?._id);
if(!user){
throw new ApiError(401, "Invalid refresh token") // Error Handing
}
if(incomingRefreshToken !== user?.refreshToken){
throw new ApiError(401, "Refresh token is expired or used") // Error Handing
}
const options = {
httpOnly: true,
secure: true,
};
const {accessToken, newRefreshToken} = await generateAccessAndRefreshTokens(user_id);
return res.status(200).cookie("accessToken", accessToken, options)
.cookie("refreshToken",newRefreshToken, options)
.json(
// Api Response Handling
new ApiResponse(200, {refreshToken: newRefreshToken, accessToken}, "Access token refreshed")
)
} catch (error) {
throw new ApiError(500, error?.message || "Invalid refresh token") // Error Handing
}
})
0
Subscribe to my newsletter
Read articles from Nikhil Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by