I am trying to protect a route in my node.js application such that if the user wants to go to the page /post
they have to come from /blog
. If the user comes from anything other than /blog
they are to be redirected to /
. I have the following code that uses the http referrer
let ref = req.headers.referer;
if ((ref === undefined) || (!ref.includes('blog'))) {
res.redirect('/')
}
It seems to work well if I console.log for testing but if I do res.redirect, I get the error
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
.
How can I use the referrer to protect the route.
Should there be any other way of accomplishing this without using referring: all suggestions are welcome.
Thanks in advance