How to force client redirect to login page with express post request?

Viewed 243

I have secure backend routes which run a verifyJWT function before continuing to retrieve data. Is there a way to force a redirect on the client side to the login page if the token is expired or is invalid?

When I used res.redirect("/login") it would have no effect on client side.

Here is the code for my routes.


const verifyJWT = (req, res, next) => {
    const token = req.headers.cookie.split("=")[1]
    if (!token) {
        console.log("No token")
    } else {
        jwt.verify(token, "mySecret", (err, decoded) => {
            if (err) {
                res.redirect("/login")
            } else {
                req.userID = decoded.id
                next()
    }})}}

One of my routes I have tested redirect on.


app.post("/getphotos", verifyJWT, (req, res) => {
    const userID = req.userID
    db.query("SELECT id, photourl, favorite, photoKey FROM photos WHERE userID = (?) AND trash = 0", 
    [userID], 
    (err, result) => {
        err ? console.log(err) : res.status(200).send(result)
    })
})
1 Answers

After reading up on routing with express I learned that redirecting must be done client side on post requests, here is how I implemented it.

If you need to log a user out for whatever reason (e.g. their JWT token expired), you can simply re-route in the backend to the logout route res.redirect("/logout").

app.get("/logout", (req, res) => {
    res.send({redirect: "/login"})
})

Then, on the client side you can check if the response is a redirect and then simply redirect them to whichever page you want.

async function getData() {
      const response = await axios.post("http://localhost:3001/getData", {body}, {withCredentials: true})
      if (response.data.redirect) {
        history.replace(`${response.data.redirect}`)
      }
    }
Related