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?
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/4.0/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.
I know it's too late, but Ored's answer is not working with Nextjs.
When using a React SPA, all of the react code will run on the client's browser, and of course in that case all you need is just serve the React build artifacts as staticfiles
.
But with Nextjs using SSR, you need to run the Nextjs server (using Nodejs) and you should integrate these 2 servers (Django and Nextjs) to work together.
So, if you are starting a new project you should just use Django as a web service and let Nextjs to be the interface of your application, but if you already have a Django application and want to use Nextjs, check out following article and GitHub repo:
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