I have a react frontend made with create-react-app
to deploy a production build of this I just do npm run build
. My app uses a Django Rest FrameWork API backend.
How can I setup the app for deployment on a single server. Is there a way I can store the React Frontend and route to it in Django and have requests from the Frontend hit a api/
view or endpoint.
What are the best strategies for deploying something like this or is it better to host the Frontend and Backend desperately on different servers?
Basically: How do I combine my react frontend build into Django DRF for deployment?
You can use django as a container for your react app. Run "npm run build" inside your react project root folder. It will generate build directory and bundle all the javascript files. Put this build folder inside the root directory of your django project. and make the following changes in settings.py file:
STATICFILES_DIRS = (
...
os.path.join(BASE_DIR, 'build/static'),
os.path.join(BASE_DIR, 'build')
...
)
and in urls.py make an entry like :-
url(r'^$', mView.login, TemplateView.as_view(template_name = 'index.html'))
Make api calls from react app using 'axios' or native fetch api.
After this whenever you hit the url for your django project it'll be redirected to the react app. You can host this with apache wsgi. Works fine for me.
Following link might help: https://alphacoder.xyz/dead-simple-react-django-setup/