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?
With Django for backend and React for frontend, nothing can stop you from creating a brilliant web app.
React will consume your Django REST API. React will make HTTP requests to your REST API in order to fetch and set data. React, with the help of Webpack (module bundler) & Babel (transpiler), will bundle and transpile your Javascript into single or multiple files that will be placed in the entry HTML page.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With