user3453202
user3453202

Reputation: 87

Dynamic routing with express framework in node

I'm using express framework 4.0 for my node js server . I was wondering if there was any way to remove routes dynamically at runtime

var express = require('express');
var router = express.Router(/*Options */);

router.get('/', function (req, res)
{
    res.render('index', {title: "Home"});
});
router.get('/features', function (req, res)
{
    res.render('features', {title: "Features"});
});
//Hook into the routing system
module.exports = function(app,rootPath)
{
    app.use(rootPath, router);
};

This is a trivial example, but how could I remove the /features path from the routing table?Additionally is it possible to overwrite this routing path with another should I wish to update the features routing path at a later date ?

Upvotes: 1

Views: 329

Answers (1)

robertklep
robertklep

Reputation: 203534

AFAIK you can't delete a route dynamically (at least not in a nice way), but you can use a filtering middleware to disallow access to a route when a certain condition is set.

For example:

var allowRoute = true;
var filterMiddleware = function(req, res, next) {
  if (allowRoute !== true) {
    return res.status(404).end();
  }
  next();
};

app.get('/features', filterMiddleware, function(req, res) {
  res.render('features', { title: 'Features' });
});

You toggle allowRoute to enable or disable access to the route (obviously, depending on the exact use case you could also use properties in req to enable/disable access to the route).

A similar setup could be used to overwrite the route handler with another one, although I'm beginning to wonder what you are trying to accomplish and if overwriting route handlers is the solution for that.

Upvotes: 2

Related Questions