Reputation: 4088
Is it OK to deploy a react-router
based webapp to production running under a node.js
server? Deploying static files prevents links like server.com/about
from working unless index.html
is loaded first. One can get around this by using HashRouter
but it seems old school to do down that route.
index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import App from './js/App';
import About from './js/About';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
import { BrowserRouter as Router, Route } from 'react-router-dom';
ReactDOM.render(
<Router>
<App>
<Route path='/about' component={About} />
</App>
</Router>
, document.getElementById('root'));
registerServiceWorker();
Upvotes: 2
Views: 269
Reputation: 4088
Not the prettiest solution but resolving to something like this alongside the nginx try_files $uri $uri/ /index.html;
does the trick.
class OnLoadHack extends Component {
componentDidMount() {
const { location, match, history } = this.props;
if(process.env.NODE_ENV !== 'development' && !match.isExact){
history.push(location.pathname + location.search)
}
}
render() {
return null
}
}
ReactDOM.render(
<Router>
<App>
<Route path='/' component={OnLoadHack} />
<Route path='/about' component={About} />
</App>
</Router>
, document.getElementById('root'));
registerServiceWorker();
Upvotes: 0
Reputation: 9681
you can use nginx fall back any route (eg. server.com/about) to the index.html
for example
location ^~ / {
alias /usr/local/theapp/dist;
try_files $uri $uri/ /index.html;
access_log /var/log/nginx/theapp/acces.web.log;
error_log /var/log/nginx/theapp/error.web.log debug;
}
# assets
location ~ ^/.+\..+$ {
try_files $uri =404;
alias /usr/local/theapp/dist;
error_log /var/log/nginx/theapp/error.web.log debug;
}
Upvotes: 1