'Dynamic endpoint with express

I'm trying to generate a dynamic URL that will change everytime an endpoint is called So I have this simple function in Node.js to create a dynamic url:

var path = crypto.createHash('md5').update(`${Date.now()}`).digest("hex");

function createNewPath(){
  path = crypto.createHash('md5').update(`${Date.now()}`).digest("hex");
}

and this simple code to receive the request:

app.use('/'+path, function(req,res){
  createNewPath();
  res.send("<h1>Welcome!<h1>");
});

The problem is that app.use does not reload the value in "path" so the initial url asigned stays the same, any ideas?

Been breaking my head and got nothing



Solution 1:[1]

Don't create the route dynamically. Set it up in advance. Check the hash inside it.

Create a route which takes the hash as a param.

Return an error if it doesn't match.

app.get("/:hash", (req, res) => {

    if (req.params.hash === path) {
        return res.send("<h1>Welcome!<h1>");
    }
    return res.sendStatus(404);
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quentin