How to Serve Django and React on the Same Port

01/15/2021

In this post I will describe how to serve your Django and React routes from the same port.  Before we get started, your project structure should look something like this:

1. In djangoproject/settings .py add the following lines of code. 

# in settings.py
import os # 1. Add this import
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 2. Add the root folder of frontend to serve front and back end at port 8000.
'DIRS': [os.path.join(BASE_DIR, 'frontend')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATICFILES_DIRS = (
# 3. Add the build directory from the frontend directory to serve front and back end at port 8000.
os.path.join(BASE_DIR, 'frontend', "build", "static"),
)
2. In djangoapp1/views add a view to render the frontend index.html file from the build directory.


# in views.py
def index(request):
# Add a view that renders the frontend build directory to serve front and back end at port 8000.
return render(request, "build/index.html")
3. In djangoproject/urls.py add the path to the view we just created.


# urls.py
from backend_apps.food_app.views import index
urlpatterns = [
path('admin/', admin.site.urls),
# Route “host:8000/” to the view that renders the frontend build to serve front and back end at port 8000.
path("", index, name="index"),
]

Now if you:

  1. cd djangoproject/frontend
  2. install your node packages: npm install
  3. create your build directory: npm run build
  4. start your frontend server: npm start
  5. cd .. 
  6. start your virtual env: source env/bin/activate (or however you start your virtual env)

  7. start your backend server: python manage.py runserver

You should be able to see your react app at localhost: 8000/!



Feel free to leave me a comment to let me know what you thought of this article. Thank you!

© 2021 Casey Roby. All rights reserved.
Powered by Webnode
Create your website for free! This website was made with Webnode. Create your own for free today! Get started