Home > Enterprise >  Which status code should be sent to client when accessToken has expired and the client needs to send
Which status code should be sent to client when accessToken has expired and the client needs to send

Time:11-24

I am building an API which uses jwt for authentication. I use a middleware to decode the token and set the req.user before every route.

app.use(async (req, res, next)=>{
    const token = req.headers.accessToken;
    if(!token){
        req.user = undefined;
        next()
    }
    try{
        const user = await jwt.verify(token, SECRET)
        req.user = user
        next()
    }catch(err){ // token present but invalid
        res.status(which status to use?).json(err)
    }   
})

If the token is present but is invalid/expired, I want to ask the client to send the refresh token. Which status code should I use. I could use a 403 which means unauthorized, but if the token has just expired, the user is authorized but only needs a new token.I dont want the client to confuse this 403 status with the one sent when the user is actually not authorized to access a resource.

Since I was not able to find the answer on google, I suspect that this is not the way to handle tokens. Is there a better way?

CodePudding user response:

401 - Unauthorized : 401 - is the status code used when the client request has not been completed because it lacks valid authentication credentials for the requested resource.

Have a look at this resource once :

  • Related