Blog>
Snippets

Conditional Route Handlers

Show how to conditionally handle routes based on custom logic, such as feature flags or experimental features toggling.
const express = require('express');
const app = express();

// Feature flag variable
global.featureFlags = {
    newFeatureActive: false
};

// Middleware for conditional routing
const featureFlagMiddleware = (req, res, next, flagName) => {
    if (global.featureFlags[flagName]) {
        next('route'); // Skip to next route
    } else {
        next(); // Continue to current route's handler
    }
};

// Conditional route: if newFeatureActive, use the new handler
app.get('/feature', (req, res, next) => featureFlagMiddleware(req, res, next, 'newFeatureActive'),
    (req, res) => {
        // Old feature logic
        res.send('Old Feature');
    }
);

// New feature route
app.get('/feature', (req, res) => {
    // New feature logic
    res.send('New Feature');
});

// Server start
app.listen(3000, () => {
    console.log('Server listening on port 3000');
});
An Express.js application example with conditional route handling. A middleware is created to check if a certain feature flag is active and conditionally route the request to the corresponding handler. If the feature flag is active, it will route to the new feature handler, otherwise to the old one.