DEV Community

Cover image for How and why you should use Next.js with Django
Matt Angelosanto for LogRocket

Posted on • Updated on • Originally published at blog.logrocket.com

How and why you should use Next.js with Django

Written by Oyinkansola Awosan✏️

Next.js is a frontend JavaScript framework built on React's UI library that is lightweight, server-rendered, and flexible. Developers typically use Next.js to build static, fully interactive sites and apps that are fast and easy to use.

Django is a free and open source web development framework built on the Python language that provides a flexible, efficient, and easier way to build web applications. Both frameworks efficiently handle a web application's frontend and backend, so it's unsurprising that their combination has a few use cases, including building ecommerce websites, marketplace management websites, real-time chat apps, and job portal websites, to name a few.

In this tutorial, we'll explore the reasons why you should consider using Next.js with Django, covering a simple example. Let's get started!

Table of contents

How to use Next.js with Django

You can use Next.js for the frontend while using Django to power and store information on the backend. In addition, using the Django Rest Framework, you can build APIs that power your website at record speed.

Using Next.js and Django together simplifies implementing CRUD features when performing both server-side and client-side rendering. For example, since Django ships with an admin panel that covers everyday CRUD admin tasks, it takes very little time to build a custom admin.

Let's cover two potential options for setting up Next.js with Django.

Using django-nextjs

One easy way to use Next.js and Django together is by installing django-nextjs. This package runs both Django and Next.js servers simultaneously, enabling Django to handle web requests and Next.js as an internal service that generates the HTML.

To get started with django-nextjs, first install it by running the code below in a Python environment:

pip install django-nextjs
Enter fullscreen mode Exit fullscreen mode

django-nextjs has already integrated Django and Next.js, allowing you to start your project in no time.

Manually implementing Django with Next.js

To manually build a project with Next.js and Django, you'll have to create two different folders to hold the frontend and backend, respectively. This is required for whatever use case or project you have in mind.

After setting up your Django app, you can create your Django API using the Django Rest Framework. Once your server is set up, your admin is accessible, and you add your data, you can go ahead and configure the Django Rest Framework, which enables you to convert your application into an API.

You'll need the Django Rest Framework to enable Next.js to access and collect the data you've set up in your database with Django. To do so, you’ll need to set up your URL, views, and serializer folders, which are all interconnected and integral to your Django and Next.js web app functioning properly.

First, install the Django Rest Framework by running the code below:

pip install djangorestframework
Enter fullscreen mode Exit fullscreen mode

Next, you need to go into the settings of your backend project and add the code below into the INSTALLED_APPS section, as directed by the official documentation:

rest_framework
Enter fullscreen mode Exit fullscreen mode

The code above activates the REST framework within your Django application, as seen in the image below: Code Activate Rest Framework For added security, you can add the code block below, which defines the default permissions. This code block ensures that anonymous people don’t have access to edit the database. Instead, they have read-only access:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}
Enter fullscreen mode Exit fullscreen mode

The image below shows an example of what it should look like within your app: Serializer Example Django App

The serializer file is important, formatting the data in such a way that it can be sent across to Next.js. You should create your serializer file as a Python file under your backend Django folder, serializers.py:

from rest_framework import serializers
from .models import Category, Product, ProductImage

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductImage
        fields = ["image", "alt_text"]

class ProductSerializer(serializers.ModelSerializer):
    product_image = ImageSerializer(many=True, read_only=True)
    class Meta:
        model = Product
        fields = ["id", "category", "title", "description", "slug", "regular_price", "product_image"]

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ["name", "slug"]
Enter fullscreen mode Exit fullscreen mode

You should also create your views file as a Python file, giving us a views.py file. The views.py file is connected to our URLs, performing the required actions and collecting data. Below is the code for the views.py file:

from django.shortcuts import render
from rest_framework import generics
from . import models
from .models import Category, Product
from .serializers import CategorySerializer, ProductSerializer

class ProductListView(generics.ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

class Product(generics.RetrieveAPIView):
    lookup_field = "slug"
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

class CategoryItemView(generics.ListAPIView):
    serializer_class = ProductSerializer
    def get_queryset(self):
        return models.Product.objects.filter(
            category__in=Category.objects.get(slug=self.kwargs["slug"]).get_descendants(include_self=True)
        )

class CategoryListView(generics.ListAPIView):
    queryset = Category.objects.filter(level=1)
    serializer_class = CategorySerializer
Enter fullscreen mode Exit fullscreen mode

The url.py file is important to link the different pages and products on our site:

from django.urls import path
from . import views
app_name = "JExpress"
urlpatterns = [
    path("api/", views.ProductListView.as_view(), name="store_home"),
# lists all the products in the database

    path("api/category/", views.CategoryListView.as_view(), name="categories"),

    path("api/<slug:slug>/", views.Product.as_view(), name="product"),
    path("api/category/<slug:slug>/", views.CategoryItemView.as_view(), name="category_item"),
]
Enter fullscreen mode Exit fullscreen mode

Why should you use Next.js with Django?

Access to modern SEO tools

The combination of Next.js and Django can work wonders for SEO purposes. In addition to the server-side rendering capabilities of Next.js, it provides access to many tools without the SEO issues that may come with a single page application. Many developers would argue that Next.js is even better for SEO than React.

Fast development time

Django has a preexisting, ready-to-use admin. Coupled with the fact that both the frontend and backend are separated, this leads to a faster development time since developers do not need to start from ground zero.

The separate architecture also makes it easier to test the application, detect bugs, and make necessary updates and changes.

User experience

Every application is built with the prospective users in mind. Building with Next.js and Django guarantees a faster loading time and an overall better experience for users. The transition of data in the background will be faster and less noticeable by users.

Good code management

Due to the separation of the frontend from the backend, you can easily achieve good code management using these Django and Next.js. Developers can easily deploy the backend without redeploying the frontend and vice versa.

Customizations

Both frameworks support high level customizations, making your application more expandable and suitable for high-level functions.

Multiple teams support

Due to the architecture of our Next.js and Django application, multiple teams can work on the application with ease without having to depend on one another to get work done. The frontend team can easily work on the frontend, while the backend team can simultaneously work on the backend part of the application.

Conclusion

Using Next.js with Django is straightforward and easy, providing a great UX. Not only does the combination work for simple applications, with the addition of a few technologies, the combination would work for larger and more complex applications intended for both web and mobile.

In this article, we reviewed some of the benefits of combining Next.js and Django, and we explored two methods for getting started. Be sure to leave a comment letting me know what type of application you build using these two frameworks.


LogRocket: Full visibility into production Next.js apps

Debugging Next applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

LogRocket signup

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens on your Next app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your Next.js apps — start monitoring for free.

Top comments (1)

Collapse
 
petergamer98 profile image
Petergamer98

Great post