Handling trailing slashes in connect-history-api-fallback and Express

Viewed 169

I'm using connect-history-api-fallback to handle calls to routes("pages") handled by React Router in a React SPA. It's working great, except that any React Router "page" that's entered with a trailing slash fails.

https://my.app/signup - works. https://my.app/signup/ - fails.

Normally, Express will handle a trailing slash and just serve the url without it (so, you enter https://my.app/signup/, Express gives you https://my.app/signup). This is the behavior of other routes not using the history-connect middleware in the same app, and it's the behavior I'd like here, as well.

The only thing I could think of was to pass in rewrites to handle the trailing slash:

import history from 'connect-api-history-fallback';

// ...setup 

app.use(
  history({
    rewrites: [
      {from: /\/signup\//, to:'/signup'}
    ]
  }),
  express.static(path.join(dirname, 'some/directory'))
);

However, this fails.

And it doesn't even make it to my React app (unlike just calling a route that doesn't exist, like https://my.app/fakeroute, which loads the app with no content), so it's not an issue of the routes within React.

Does anyone know the correct way to do this? As a popular module, I can't imagine it can't handle trailing slashes.

1 Answers

Please make sure you're running the latest version of connect-history-api-fallback. I just tested it and it's working correctly with /signup and /signup/

const express = require('express');
const history = require('connect-history-api-fallback');

const app = express();

app.use(
    history({
        rewrites: [
            { from: /\/signup/, to: '/signup'}
        ]
    })
)

app.get('/signup', function(req, res) {
    res.send("signup");
})

app.listen(8080);
Related