DEV Community

Cover image for Deploying React with Express with route integrity
Médéric Burlet for Pixium Digital

Posted on

Deploying React with Express with route integrity

Background

As you may or may not know React often uses routing through the browser history API

A few of the common libraries that you might encounter would be:

These libraries will let you define routes and which components are being rendered.

Quick Example:

<Route path="/about"><AboutPage/></Route>
<Route path="/user/:id">
    {params => <UserPage id={params.id} />}
</Route>
Enter fullscreen mode Exit fullscreen mode

Running this in dev mode will work fine.

awesome


Issue

If you build the react app and try to host it with express you'll notice we run in an issue:

import * as express from 'express'
const app = express()
app.use(express.static(configuration.buildDirectory));
app.listen(8080, () => {
    console.log(`Server started on port 8080`);
});
Enter fullscreen mode Exit fullscreen mode

If you navigate to http://127.0.0.1:8080 you'll see your react app.

However if you navigate to http://127.0.0.1:8080/about

You will receive an error:

Can't GET /about
Enter fullscreen mode Exit fullscreen mode

not working


Solving the Issue

Our issue comes from the fact that express will only allow the route '/' to be used.

The idea is that we want to preserve the routes but still display our built index.html

For this we can add the following statement:

app.all('*', (req, res) => {
    res.sendFile(path.join(configuration.buildDirectory, '/index.html'), (err) => {
        if (err) {
            res.status(500).send(err)
        }
    })
});
Enter fullscreen mode Exit fullscreen mode

This means that for every route we will render the index.html however since we are not redirecting we will preserve the URL scheme.

mission accomplished


Pixium Digital - Shaping your project with technology and innovation
https://pixiumdigital.com
https://github.com/pixiumdigital

Top comments (0)