//URL Shortener //npm install express express-rate-limit shortid /* TODO for production environment: Save Shortened URLs in a SQL Database (or noSQL) Choose a different storage for express-rate-limit (redis, etc.) Use NodeJS Cluster to get better performance Better tune the rateLimit */ var express = require("express"); var rateLimit = require("express-rate-limit"); var shortid = require("shortid"); const PORT = 3000; const HOSTNAME = "http://localhost:3000/"; //^ Main Location with trailing slash var app = express(); app.use(express.json()); app.use(express.urlencoded({ extended:true})); var urls = {}; const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100 // limit each IP to 100 requests per windowMs }); if (app.get('env') === 'production') { app.set('trust proxy', 1) // trust first proxy } app.use("/s",limiter); //only limit url shortenings, not website hits app.get("/",function(req,res){ res.send(html); }); app.post("/s",function(req,res){ //use redis or mysql here if(req.body.url==""||req.body.url==null){ res.redirect("/"); return; } let id = shortid.generate() urls[id] = req.body.url; res.send("

"+HOSTNAME+id+"

"); }); app.get("/:id",function(req,res){ if(req.params.id in urls){ res.redirect(urls[req.params.id]); } }); const html = ` URL Shortener | shira.at

URL Shortener


` app.listen(PORT, () => console.log("Now listening on *:"+PORT));