Vite with react-router-dom

Viewed 1302

I am developing a webapp with two pages using Vite and react-router dom, everything was working fine while in development mode. But when I build de app, the only page that works is the index (path="/") I am using the exact property.

1 Answers

The reason it happens is because build behaves differently. When you run your application in development mode, it means your application is now running on a server (your PC hosts the application - a node js app is running and your application is running on it).

When you build your application, the "build" directory is generated, but there is no server running anymore. So either create a server that will "host" the application, or don't use react-router-dom (you can try to implement this by yourself)

Now, when you're using react-router, you ideally want to route all requests to build/index.html. So you may build a proxy server to serve your index.html and static files as follows (using Express.js):

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(express.static(path.join(__dirname, 'build')));

app.use('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'build/index.html'));
});

app.listen(process.env.PORT || 3000, () => console.log(`Running on PORT ${process.env.PORT || 3000}`));
Related