Nodejs redirect to intended URL after login

As I continue to recreate my website in nodejs, I find myself going back to my old topics and responses to refresh my memory on how I set things up in php and adapt it to nodejs.

In my current todo to accomplish, I need to redirect a user back to the page they were on after they get successfully logged in.

I reviewed the following topic:

However, this solution does not appear to work in a nodejs project because the redirect is on the server side, not the client side.

I need advice how to redirect a user to the page they were on prior to being directed to the login page. To further complicate matters a little bit, I use the Facebook Auth, so its not a typical login form, rather just an anchor button.

You have the referer url available in $_SERVER.HTTP_REFERER

So if page A redirects to page B(your login) you can then redirect them back to A as it’s stored in the referer header.

Edit: Actually after a second thought I think this won’t work as the restrict redirect happens on server so that http header will not be set as it comes from the browser.

You could however store in a server session variable the url($_SERVER.URL) you navigated to just before the restrict happens and then redirect to that after a succesful login.

I receive the following error when using the $_SERVER.URL:

{“status”:“500”,“message”:“Http status code 400. {“error”:{“message”:“This authorization code has been used.”,“type”:“OAuthException”,“code”:100,“error_subcode”:36009,“fbtrace_id”:“Ab7wxb5nLwUXfh9wPJObOOa”}}”,“stack”:“Error: Http status code 400. {“error”:{“message”:“This authorization code has been used.”,“type”:“OAuthException”,“code”:100,“error_subcode”:36009,“fbtrace_id”:“Ab7wxb5nLwUXfh9wPJObOOa”}}\n at IncomingMessage. (/opt/node_app/lib/oauth/index.js:95:39)\n at IncomingMessage.emit (events.js:327:22)\n at endReadableNT (_stream_readable.js:1221:12)\n at processTicksAndRejections (internal/process/task_queues.js:84:21)”}

I think it is because I use the Facebook Auth, it is redirecting back in a loop after being approved.

Here’s my server action.

$_SERVER.URL will redirect to itself, so causing a loop. $_SERVER.HTTP_REFERER is a better choice. Also you need to store it on the first visit and then retrieve it again on the second visit when coming back from the login. Logic can be a bit difficult, it is easier to just redirect the user to the index page after they logged in.

There are situations where this wouldn’t work very well. Eg during a checkout process, where someone can log in if they an account; going back to the index page having logged in wouldn’t be a good option. There are many similar situations.

I mention this because this type of thing is not much of a problem with PHP. Is it fundamentally more difficult using NodeJS? I have yet to start using NodeJS but at some point, I would like to experiment with it.