I\'m trying to create a simple CMS with express.js that dynamically creates routes. It gets a JSON from a database that looks like this:
pagesfromdb = {
I would be very careful trying to create or destroy routes at runtime. Although you can change the data structures yourself, I do not believe these are documented as API's, so you risk this breaking if/when you upgrade Express.
This could also serve as a memory constraint if you create a new route for each database object because the set of pages can grow to who knows how big.
Look at it like this... you don't want new routes; you want to add URL's to existing routes. If you are adding a route, that means you want some URL to map to some distinct function. But you are mapping each URL to the same function. In essence, you are only adding routes by side effect. What you care about is that some dynamic set of URL's map to a specific function.
Can you instead use a wildcard to map the URL pattern to a specific function, like
app.get('/pages/*', function(req, res) {
var page = pagesfromdb[key];
if (page != null) {
res.render(page.render, page.language)
}
else {
res.send(404);
}
});
And manage the pagesfromdb mapping outside of the express layer. You can use direct database access, cache + database access or a timer-based refresher, whatever performs best for you.