Search code examples
reactjsnode.jsreact-routervitenpm-build

Npm run build/start do not get all pages


I have the following code of my routes in a react/vite app:

<Router>
   <Routes>
      <Route exact path="/" element={<LoginPage mensagemSucesso={mensagemSucesso} />} />
      <Route exact path="/criar-conta" element={<CriarConta onContaCriadaSucesso={(mensagem) => { handleRetornoSucesso(mensagem)}} />} />
      <Route exact path="/recuperar-senha" element={<RecuperarSenha onRecuperacaoSucesso={(mensagem) => { handleRetornoSucesso(mensagem)}} />} />
      <Route path="/redefinir-senha/:key" element={<RedefinirSenha onRedefinirSucesso={(mensagem) => { handleRetornoSucesso(mensagem)}} />} />
      <Route exact path="/principal" element={<AuthMiddleware><Principal /></AuthMiddleware>} />
   </Routes>
</Router>

All those pages are imported in the beginning of the file. When I run npm run dev, the URL "localhost:5173/redefinir-senha/code" works. But when I run npm run start, the same URL gets a NOT FOUND from the frontend and the console appear the message GET http://localhost:3000/redefinir-senha/code 404 (Not Found).

In package.json to check for npm run start and npm run dev:

"scripts": {
    "start": "vite build && serve dist",
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  }

Am I missing something that I have to do to work in npm run start to make it work in production environment?


Solution

  • To make the node understand routes that work dynamically, like /redefinir-senha/123 and /redefinir-senha/abc, I had to install the express with npm install express, create a server.js file on root folder with the following code:

    const express = require('express');
    const path = require('path');
    const app = express();
    const port = 8000;
    
    // Servir arquivos estáticos da pasta 'build'
    app.use(express.static(path.join(__dirname, 'dist')));
    
    // Rotas para servir a aplicação React
    app.get('/', (req, res) => {
        res.sendFile(path.join(__dirname, 'dist', 'index.html'));
    });
    
    // Rota para lidar com as rotas React que contêm parâmetros dinâmicos
    app.get('/redefinir-senha/:key', (req, res) => {
        res.sendFile(path.join(__dirname, 'dist', 'index.html'));
    });
    
    // Lidar com todas as outras rotas, redirecionando para a página inicial
    app.get('*', (req, res) => {
        res.redirect('/');
    });
    
    // Iniciar o servidor
    app.listen(port, () => {
        console.log(`Servidor Express iniciado na porta ${port}`);
    });
    

    Also, add one more script at the package.json file:

    "server": "node server.js"
    

    This way, the server worked and could get those routes dynamically. Otherwise, the npm run build only gets the routes that exists statically. For example, if have a Link element to /redefinir-senha/123, that element will be working, but if I had to access /redefinir-senha/abc, the pages would not found.