I’m trying to make a Sign Out function on React-Express Web App. But it doesn’t clear my cookie.
Code when set the cookie
res.cookie('!', t, {
maxAge: 1000 * 60 * 60 * 24 * 30,
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: "strict",
priority: "high"
})
res.status(200).json()
Code to removing the cookie
const SignOut = (_: Request, res: Response) => {
res.clearCookie('!')
res.status(200).json()
}
export default SignOut
Route
import RegCon from '../controllers/Register'
import LogCon from '../controllers/Login'
import OutCon from '../controllers/SignOut'
const router = express.Router({
caseSensitive: true,
strict: true
})
router.post('/API/register', RegCon)
router.post('/API/login', LogCon)
router.delete('/API/signout', OutCon)
React SignOut handler
const handleSignOut = async () => {
try {
await axios.delete('http://localhost:3001/API/signout')
// location.href = '/'
} catch (err) {
const XR = err as AxiosError
alert(XR.response!.statusText)
}
}
The things that makes me more even confuse is its not fall into the catch, its actually succeeded but it doesn’t clear my cookie on here
Anybody could explain why?
2
Answers
As per express documnetation here, you need to pass the options parameter which should be identical to the one that you define when you set the cookie with the exception of
expires
andmaxAge
.So, your sign out function should look something like this:
Duplicate of : res.clearCookie is not clearing cookies despite matching options
You are not sending back the request, so the
res
object here is stuck inside theSignOut
function.You need to
return
it so it is sending the response with the cleared cookies