1

I'm making Authentication system using jwt with httpOnly cookies in node.js and React.js.

Question is- How should i handle if someone explicitly delete cookie(contain accesstoken) by going to inspect> application >cookies tab in browser?

In my case it should navigate to Login page but it just stay in the home page unless refreshed.

Home.js(send request to verify token on component mount but if cookie deleted stayed on the same page insted going to login page)

   import axios from 'axios'
import React, { useEffect } from 'react'
import './Home.css'
import { useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux'
import Login from '../../Pages/Login';




function Home() {
const navigate = useNavigate()

useEffect(() => {
    axios.get('http://localhost:9000/auth/redirecthome', { withCredentials: true })
        .then((res) => {
            console.log(res, 'response')
        })
        .catch((err) => {
            console.log(err)
            navigate('/login')

        })
}, [])

return (
    <div className='Home'>Home</div>

    )
}

export default Home

  • You can use an Context api for Auth and logout the user when you fail to get an auth status from backend. Since you are using httpOnly you cannot access the cookie and check its presence. – Kaneki21 Jul 10 '22 at 15:03
  • @Kaneki21, Actually i tried to use redux but even after condition rendering it only works after when i refresh the page – Sharanjeet Singh Jul 10 '22 at 15:07
  • @Kaneki21 because as i load the page it goes to middleware(backend to verify token) and once it verifies it just doesn't bother after that if cookie is still there unless refresh – Sharanjeet Singh Jul 10 '22 at 15:09
  • yes you have to trigger some event for checking the auth status, some sort of scheduled action might be an option. But in real life nobody would do that and if somebody does then you have to use axios interceptor for getting the token and then make the request – Kaneki21 Jul 10 '22 at 15:11
  • @Kaneki21, Okay was just curious, thank you for the answer – Sharanjeet Singh Jul 10 '22 at 15:15

0 Answers0