I've integrated Reactjs with Django by having a function to access build/index.html
. The below codes show how I do that.
config/urls.py
urlpatterns = [
...
re_path(r'search/', react_views.ReactAppView.as_view()),
]
PROJECT_NAME/views.py
class ReactAppView(View):
def get(self, request):
try:
with open(os.path.join(str(settings.BASE_DIR), 'frontend', 'build', 'index.html')) as file:
return HttpResponse(file.read())
except:
return HttpResponse(
"""
Build your React app.
""",
status=501,
)
ReactAppView
function accesses index.html
which is created with yarn build
on React side. Basically, I used React just for search view, and other than search view, I used jQuery as it was developed with jQuery first.
Since I found that I need Next.js to use Server Side Rendering (SSR) with React, I've been trying to migrate React app to Next.js. But, Next.js doesn't have index.html
. It just has pages/index.js
instead.
I've tried very hard to figure out how to integrate Django with Next.js, but I can't find any helpful resource. Can anyone help me about this?
Note this answer assumes you are not making use of server-side rendering (SSR) features in NexJS. In these cases the bundled web app is "just" a React Single Page Application (SPA).
This is not the answer you are looking for if you are using SSR and your NextJS app is set up to forward API requests to Django. In that case look at DjangoRestFramework or Django Ninja to publish your Django views as REST APIs.
It seems like you want to serve static files (i.e. React or Next.js bundles).
Django has a guide on how to do this (via django.contrib.staticfiles
)
The simplest example (straight from the docs) is:
set the STATIC_FILES
folder:
STATIC_URL = '/static/'
Put the index.html
file there and reference it as /static/index.html
.
For more info on staticfiles
, please refer to the official documentation: https://docs.djangoproject.com/en/5.2/howto/static-files/
On the Next.js side, you need to either follow the sample at https://nextjs.org/docs/advanced-features/static-html-export or create manually an index.html
that includes all next.js bundles that you are using.