Just started with using React. I have an app created with create-react-app
which should be running on a sub-directory
while making API calls to a different path.
React App:
location on server: /var/www/myapp/build
endpoint: https://foo.example.com/analytics
Data API endpoint: https://foo.example.com/api/data
Nginx setup
location /analytics {
root /var/www/myapp/build;
try_files $uri /index.html;
}
When setting "homepage":"https://foo.example.com/analytics"
in the client's package.json
, all the resource paths seem to be correct (i.e. https://foo.example.com/analytics/static/...
), but when checking networking no request to .../api/data
shows up in my browser's networking inspector and the app doesn't properly spawn.
Using absolute paths in the App's API call
(fetch('https://foo.example.com/api/data')
instead of fetch('/api/data')
) doesn't seem to help, either.
When instead I set "homepage":"."
in package.json
and also change the Nginx config to serve the react build directory on server root, the app works.
server {
root /var/www/myapp/build;
}
However, in this case, the app is also available under https://foo.example.com
, which is something I don't want.
I strongly suspect this has to do with routing, but couldn't figure out how to fix it. So any help would be much appreciated!
--- Edit / Solution ---
I doubt it's the most straight forward solution, but the following setup works for me:
React App
In package.json
, set "homepage":"./analytics"
before running npm run build
Nginx config:
location = /analytics {
root /var/www/myapp/build;
try_files /index.html =404;
}
location ~ ^/analytics(.*) {
root /var/www/myapp/build;
try_files $1 $1/ /index.html =404;
}
My understanding is that the initial setup using try_files $uri
was looking for files in the root directory /var/www/myapp/build
for the full uri rather than only the path that follows /analytics
. E.g. when requesting ../analytics/css/styles.css
it would check if a file (or directory) is available under /var/www/mayapp/build/analytics/css/styles.css
which doesn't exist, so it kept serving the index.html
as fallback. Hence the regex workaround.
Feedback to improve this solution still very welcome, though.