Run express middleware for all routes except that are starting with /api?

11,224

Solution 1

Try this:

app.use(/^\/(?!api).*/, function(req, res) {
  Router.run(routes, req.path, function(Handler) {
    var markup = React.renderToString(<Handler />);
    res.send(swig.renderFile('views/index.html', { html: markup }));
  });
});

Solution 2

This is how I handle non existent api routes. I have api folder that contains all my api route, ideally each in their own js file and api/index.js requires all these routes like this

var router = require('express').Router();

router.use(require('./users'));
router.use(require('./it'));
//other routes.js

then at the end in my api/index.js I have this

router.use('/*', function(req, res) { //this will reject any /api/nonexistant routes
  res.send(500).end();
});

In my server js I include my api routes first

app.use('/api', require('./api'));
app.use(function(req, res) {
  console.log('dosomething');
  res.send('Hello something').end();
});
Share:
11,224
Sahat Yalkabov
Author by

Sahat Yalkabov

Updated on June 09, 2022

Comments

  • Sahat Yalkabov
    Sahat Yalkabov almost 2 years

    I have an Express middleware that renders React on the server like so, placed at the end, after all other routes:

    app.use(function(req, res) {
      Router.run(routes, req.path, function(Handler) {
        var markup = React.renderToString(<Handler />);
        res.send(swig.renderFile('views/index.html', { html: markup }));
      });
    });
    

    Since no route is specified this middleware will execute for all requests. I would like to exclude all /api routes from it. The problem is even if I create all API routes before this middleware, there is always a possibility for this middleware to be executed on /api/nonexistantendpoint path.

    To be more precise, I am looking for a regex that would make this middleware execute for all paths except any path starting with /api.

    Thanks!


    I have already looked at this SO post but couldn't find anything useful to me.

    And this post contains a lot of workarounds which is also not what I am looking for.

    This post asks you to conditionally check for URL inside the middleware.