Categories
Uncategorized

Redirect users based on the HTTP Request Header – Node.js

For this example it is recommended that you have the latest most stable release of Node.js + npm installed.
Now you will need express to run a simple server.

npm install express --save

Express Application

The following code makes use of the ES6 syntax.
index.js

const express = require('express')
const app = express()
cont port = 3000

app.get('/home', (req, res) => res.send('Express Application!'))

app.get('/user', (req, res) => res.send('User Area!'))

app.get('/', (req, res) => {
if (req.headers.user === 'user') {
  res.redirect('/user') 
} else {
  res.redirect('/home')
}
})

app.listen(port, () => console.log('Node.js Application is listening on port 3000!'))

Now using the command line, navigate to the directory where you have the index.js and execute the following command, which should hopefully run your application successfully on port 3000.

node index.js

Setting Headers

If you are running this on your local machine then navigate to localhost:3000 in your browser and you should be redirected to ‘/home’. When on a remote server then replace localhost with the IP address. You would also need to ensure that your port 80 is open and is forwarded to port 3000 where your application is running.
If you set your header using ModHeader (header spoofing chrome extension) in Google Chrome, with the both the key and value as user.
If you refresh the page now you should be redirected to a page that says ‘User Area!’.