I am using fetch to communicate with the node server(Express). I am building a SPA. On each request to the server I am checking if the session is valid or not. If the session is not valid I am redirecting from node to a login page. The problem is that. If the session is getting invalidated(for eg: get/post request running in the background without a page refresh) the request is failing silently. It is not getting redirected.
I had the same issue for the ajax request also. What I had done is by checking the request is xhr and accept json. Then send a json response and handle the redirect in the frond end.
if (req.xhr && req.accepts('json')) {
res.json({status:'session_timeout'});
}else{
res.redirect('/login');
}
How can I do the same by using fetch. How do I handle redirect using fetch.
Hi @jetsonjohn. This is really a usage question and we can't really write your application for you. We don't know what all the intricacies of your authentication system need to be.
From your server-side code example, it seems that you're doing things right. All what's left is that whenever you make a fetch() request, you need to parse its JSON response and check for whether the status key is equal to "session_timeout", then perform the redirect to /login manually. Which our examples in the README for how to parse JSON from responses.