Subscribe For Updates
Redirect Server With Express.js
For my job I had to write a handler to redirect vanity URLs using Clojure. This is an easier example with Node.js
const express = require('express')
const { redirectTable } = require('./redirectTable')
const PORT = 8080
const app = express()
app.get('/', (req, res) => {
res.status(200).json({ success: true })
})
app.get('/go/*', (req, res) => {
const targetUrl = redirectTable[req.url]
if (targetUrl !== undefined) {
res.setHeader("Location", targetUrl)
}
res.status(302).json({})
})
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
Redirect Table (redirectTable.js)
const payload =
[
{
"vanityURLPath": "/go/google",
"targetURL": "https://www.google.com"
},
{
"vanityURLPath": "/go/cnn",
"targetURL": "https://www.cnn.com"
},
{
"vanityURLPath": "/go/disney",
"targetURL": "https://www.disney.com"
}
]
const redirectTable = {};
payload.forEach(el => {
redirectTable[el.vanityURLPath] = el.targetURL
})
module.exports = {
redirectTable
}