mamsoudi mamsoudi - 24 days ago 7
Node.js Question

Making and changing APIs when online in Nodejs

So were trying to develop an application (or Service) with Node.js that provides each user a custom API that can be called from

. Users will be able to change/edit/remote the endpoints of the API within the application through our editor. They can add params to the endpoints, add auth, etc.

Now my question is, how can we make the API online at first, then how can we change the endpoints online without stopping the API application and running again?

P.S: APIs configuration will be saved into a JSON that will be saved to the DB and once the configuration change an event will be raised that tells us the endpoints have changed.

Answer Source

Using Express, you can add routes after the server is listening, so it's not a problem. Beware of precedence as it will be added at the bottom of the stack.

I would advise to have a db storing routes, and when running the node app (before listening) load all the routes in db and add them to the router. In order to be able to scale your app as well as being able to restart it safely.

Then start listening, and have a route for adding routes, deleting routes, updating routes etc.

Here is a simple example of adding a route after listening :

const app = require('express')();
const bodyParser = require('body-parser');


const someGenericHandler = function(req, res) {
    return res.json({ message: 'foobar' });

// it creates a route'/routes', function(req, res) {
    try {
        const route = req.body;
        app[route.method](route.path, someGenericHandler);
        return res.json({ message: `route '${route.method}${route.path}' added` });
    } catch(err) {
        return res.status(500).json({ message: err.message || 'an error occured while adding the route' });


You can try this code, paste it in a file, let say index.js. Run npm i express body-parser, then PORT=8080 node index.js, then send a POST request to http:/localhost:8080/routes with a json payload (and the proper content-type header, use postman) like this: { method: 'get', path:'/' } and then try your brand new route with a GET request @ http://localhost:8080/'

Note that if you expect to have hundreds of users and thousands of requests per minute, I would strongly advise to have a single app per user and a main app for user registering and maybe spawn a small VPS per app with some automation scripts when a user register, or have some sort of request limit per user.

Hope this helps