djangoreactjsnext.js

Is there a way to integrate Django with Next.js?


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?


Solution

  • 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:

    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.