Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 649
Jae P. Avatar asked Mar 05 '23 16:03

Jae P.


2 Answers

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.

like image 51
Oerd Avatar answered Apr 27 '23 13:04

Oerd


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:

  • Medium: Django + Next.js The Easy Way
  • Github: django-nextjs
like image 20
danial keimasi Avatar answered Apr 27 '23 13:04

danial keimasi