Bootstrap FreeKB - Node.js - Redirect to a URL
Node.js - Redirect to a URL

Updated:   |  Node.js articles

If you have not yet installed Node.js, check out my article Install Node.js on Linux.

res.redirect is typically used to do a redirect in a route.

const express = require("express")
const app = express()
const timestamp = () => Date()

app.get('/', (req, res) => {
    console.log(`${timestamp()} Hello Console`)
    res.redirect('http://www.example.com');
})

app.listen(12345)

 

If you are using plain old Javascript location.replace or location.href can be used. location.replace is typically preferred as it should not allow the user to click the back arrow in their web browser whereas location.href is like clicking on an href link that allows the back arrow key to be used to go back to the prior page.

window.location.replace('http://www.example.com');

 

Or location.href can be used. location.href is like clicking on an href link that allows the back arrow key to be used to go back to the prior page.

window.location.href = 'http://www.example.com';

 

You may also want to add the following on the page you are redirecting to.

  • The history.pushState() method modifies the browser's history stack without reloading the page
  • The popstate event is triggered when the user navigates back or forward. The code pushes a new state onto the history stack, essentially overwriting the previous state. 
<script>
  window.history.pushState(null, null, window.location.href);
  window.onpopstate = function() {
    window.history.pushState(null, null, window.location.href);
  };
</script>

 

For example, I had a Node.js Express Docker container running on one of my EC2 instance with the above markup in server.js and when I requested the URL for my Docker container on the EC2 instance I was successfully immediately redirected to https://www.freekb.net. Nice - it works!

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 7524ef in the box below so that we can be sure you are a human.