Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NGINX proxy pass to React App not working

I want to run the following projects using NGINX under a single subdomain: http://localhost:3000 (Loopback API) and http://localhost:3006 (React Application)

Both applications are running under PM2. React App is running in production (using its generated build) with the command: 'pm2 serve build 3006'.

/etc/nginx/sites-available/default

server {
listen 80;

server_name subdomain.domain.com;

location / {
    proxy_pass http://localhost:3006;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
    try_files $uri /index.html;
}

location /api {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

Loopback project under location /api es working perfectly. The issue is with my React project under my / route. When I enter to subdomain.domain.com I just get a blank page. In the developer console I'm getting the following errors:

Console log

Using http://localhost:3006 to access my React App works perfectly fine with no console issues so I'm totally sure it is something related with nginx.

I have been investigating a lot about the incorrect MIME type being loaded, but my /etc/nginx/nginx.conf is already running with the following configuration:

http {
    include /etc/nginx/mime.types;
}

I would really appreciate your help, thanks.

like image 207
Juan Pablo Avatar asked Jul 08 '26 21:07

Juan Pablo


1 Answers

Are you using Create React App? By default, its build script assumes the app is going to be served in the root directory. To correctly serve React under a subdirectory, you need to specify homepage in your package.json file.

"homepage" : "http://example.com/your-subdirectory"

Additionally, you'll want to modify server/app.js to reflect this change.

app.use('/your-subdirectory/api', require('./api'));

Lastly, and most importantly, you'll want to set a basename for React Router as well.

  const Routes = () => {
     return (
        <Router basename={'/your-subdirectory'}>
        <div>
           <Route exact path={`/`}component={App} />
        </div>
       </Router>
     )
   };
like image 151
Joven Macaldo Avatar answered Jul 11 '26 09:07

Joven Macaldo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!