I don't know how to handle 401 status request from my server, when access token is extinct. I wrote accessTokenVerify on server side:
require('dotenv').config();
const jwt = require("jsonwebtoken");
// Access Token Verify
exports.accessTokenVerify = (req, res, next) => {
if (!req.headers.authorization) return res.status(401).send({ msg: "Access Token is missing." })
const BEARER = 'Bearer';
const auth_token = req.headers.authorization.split(' ');
if (auth_token[0] !== BEARER) return res.status(401).send({ msg: "Access Token is not complete." })
jwt.verify(auth_token[1], process.env.ACCESS_TOKEN_SECRET, (err) => {
if (err) return res.status(401).send({ msg: "Access Token is invalid." })
next();
})
}
And I have refreshing access token endpoint localhost:5000/api/auth/refresh. But I don't how to implement request on client side which send refresh request when I get 401 status response.
I have this so far:
const onSubmit = (values: Values) => {
fetch("http://localhost:5000/api/posts", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({
name: "Nazwa",
text: "jakiś post",
id: "341324132"
}),
})
.then((response) => {
if (response.status == 401) {
refreshTokens();
[and what next...]
}
return response.json();
})
.then((resp) => console.log(resp))
.catch((err) => {
console.log(err);
});
};
when refreshTokens() would be send resquest to /refresh endpoint and set new tokens, but I don't know how to resend primary request (adding post).
async/await, you can achieve it likelet resp = await fetch(...); if (resp.status === 401) { await refershTokens(); resp = await fetch(...); }. (You can avoid duplication using recursion/retry by writing it in different function). - Prathap Reddy