DEV Community

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

Posted on

1 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay