8

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.

Community
  • 1
  • 1
Sahat Yalkabov
  • 32,654
  • 43
  • 110
  • 175

3 Answers3

15

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 }));
  });
});
hassansin
  • 16,918
  • 3
  • 43
  • 49
1

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();
});
kachhalimbu
  • 2,190
  • 17
  • 14
0

I'm pretty sure I had the exact same use case as Sahat, here's the syntax I used for configuring two routes to handle /api matches and misses in Express.js:

// /api/* Matches
app.get( '^/api/:params*', function( req, res, next ) {
    res.send( "Matches an /api/ route." );
} );

// /api/* Misses
app.get( /^((?!\/api\/).)*$/, function( req, res, next ) {
    res.send( "NOT an /api/ route." );
} );

This assumes that all of your API routes follow a pattern of /api/*.

Kevinleary.net
  • 8,851
  • 3
  • 54
  • 46