Skip to main content

Server-Side Rendering for React components in Django

Project description

Django React Kit

A powerful Django package that enables server-side rendering (SSR) of React components with file-based routing, similar to Next.js but integrated seamlessly with Django.

๐Ÿš€ Features

  • Server-Side Rendering (SSR): Render React components on the server for better SEO and performance
  • File-Based Routing: Organize your React pages using a familiar file system structure
  • Django Integration: Access Django ORM, authentication, and middleware from React components
  • Hot Module Replacement: Fast development with HMR support
  • TypeScript Support: Full TypeScript support for type-safe development
  • Easy Installation: Install via PyPI and integrate with existing Django projects

๐Ÿ“ฆ Installation

pip install django-react-kit

๐Ÿ› ๏ธ Quick Start

1. Add to Django Settings

Add django_react_kit to your INSTALLED_APPS:

# settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_react_kit',  # Add this
    # ... your other apps
]

2. Configure URLs

Include the React Kit URLs in your main URL configuration:

# urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    # ... your other URL patterns
    path('', include('django_react_kit.urls')),  # Add this last (catch-all)
]

3. Build React Components

python manage.py reactbuild

For development with hot module replacement:

python manage.py reactbuild --watch

4. Run Django Server

python manage.py runserver

Visit http://127.0.0.1:8000/ to see your React-rendered Django app!

๐Ÿ“ File Structure

After installation, Django React Kit provides this structure:

django_react_kit/
โ”œโ”€โ”€ frontend/
โ”‚   โ”œโ”€โ”€ app/
โ”‚   โ”‚   โ”œโ”€โ”€ page.tsx          # Home page component
โ”‚   โ”‚   โ”œโ”€โ”€ layout.tsx        # Root layout component
โ”‚   โ”‚   โ””โ”€โ”€ about/
โ”‚   โ”‚       โ””โ”€โ”€ page.tsx      # About page component
โ”‚   โ”œโ”€โ”€ ssr.js               # Server-side rendering script
โ”‚   โ”œโ”€โ”€ main.tsx             # Client-side entry point
โ”‚   โ””โ”€โ”€ package.json         # Frontend dependencies
โ”œโ”€โ”€ templates/
โ”‚   โ””โ”€โ”€ django_react_kit/
โ”‚       โ””โ”€โ”€ index.html       # Base HTML template
โ”œโ”€โ”€ management/
โ”‚   โ””โ”€โ”€ commands/
โ”‚       โ””โ”€โ”€ reactbuild.py    # Build management command
โ”œโ”€โ”€ views.py                 # ReactView class
โ””โ”€โ”€ urls.py                  # URL routing

๐ŸŽฏ Creating Custom Views

Extend the ReactView to provide custom data to your React components:

# views.py
from django_react_kit.views import ReactView
from .models import Post

class BlogView(ReactView):
    def get_data(self, request):
        posts = Post.objects.all()
        return {
            'posts': [
                {
                    'id': post.id,
                    'title': post.title,
                    'content': post.content,
                    'created_at': post.created_at.isoformat(),
                }
                for post in posts
            ],
            'user': {
                'is_authenticated': request.user.is_authenticated,
                'username': request.user.username if request.user.is_authenticated else None,
            }
        }

๐Ÿ“„ Creating React Pages

Create new pages by adding files to the frontend/app/ directory:

// frontend/app/blog/page.tsx
import React from 'react';

interface BlogPageProps {
  data?: {
    posts: Array<{
      id: number;
      title: string;
      content: string;
      created_at: string;
    }>;
    user: {
      is_authenticated: boolean;
      username?: string;
    };
  };
}

const BlogPage: React.FC<BlogPageProps> = ({ data }) => {
  return (
    <div>
      <h1>Blog Posts</h1>
      {data?.posts?.map(post => (
        <article key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.content}</p>
          <small>Published: {new Date(post.created_at).toLocaleDateString()}</small>
        </article>
      ))}
    </div>
  );
};

export default BlogPage;

โš™๏ธ Configuration

Environment Variables

Set these in your Django settings or environment:

# settings.py

# Node.js executable path (optional, defaults to 'node')
NODE_PATH = '/usr/local/bin/node'

# Frontend build directory (optional)
REACT_BUILD_DIR = BASE_DIR / 'django_react_kit' / 'frontend'

Custom SSR Configuration

You can customize the SSR behavior by overriding methods in ReactView:

from django_react_kit.views import ReactView

class CustomReactView(ReactView):
    def get_ssr_timeout(self):
        """Override SSR timeout (default: 10 seconds)"""
        return 15
    
    def handle_ssr_error(self, error, request):
        """Custom error handling for SSR failures"""
        if settings.DEBUG:
            return HttpResponse(f"SSR Error: {error}", status=500)
        # Fallback to client-side rendering in production
        return render(request, 'django_react_kit/index.html', {
            'rendered_content': '<div>Loading...</div>',
            'initial_data': json.dumps(self.get_data(request)),
            'path': request.path
        })

๐Ÿ”ง Management Commands

reactbuild

Build React components for production:

python manage.py reactbuild

Options:

  • --watch: Enable watch mode for development
  • --production: Build for production environment

๐Ÿš€ Deployment

Production Setup

  1. Build the frontend for production:
python manage.py reactbuild --production
  1. Ensure Node.js is available on your server

  2. Configure your web server (nginx/Apache) to serve static files

  3. Set appropriate Django settings:

# settings.py (production)
DEBUG = False
ALLOWED_HOSTS = ['your-domain.com']

Docker Integration

# Dockerfile
FROM python:3.11

# Install Node.js
RUN curl -fsSL https://deb.nodesource.com/setup_18.x | bash -
RUN apt-get install -y nodejs

# Install Python dependencies
COPY requirements.txt .
RUN pip install -r requirements.txt

# Copy project
COPY . /app
WORKDIR /app

# Build React components
RUN python manage.py reactbuild --production

CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ†˜ Support

๐Ÿ™ Acknowledgments

  • Inspired by Next.js file-based routing
  • Built with Django and React
  • Thanks to the Django and React communities

Django React Kit - Bringing modern React development to Django with SSR! ๐ŸŽ‰

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_react_kit-1.0.1.tar.gz (16.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_react_kit-1.0.1-py3-none-any.whl (16.1 kB view details)

Uploaded Python 3

File details

Details for the file django_react_kit-1.0.1.tar.gz.

File metadata

  • Download URL: django_react_kit-1.0.1.tar.gz
  • Upload date:
  • Size: 16.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.5

File hashes

Hashes for django_react_kit-1.0.1.tar.gz
Algorithm Hash digest
SHA256 0571dc93bdd2f9b39ebbf58f0f2559a7a8fed22f304d5dbe5a86f7482d2cec6c
MD5 142310363a9463f2340596a64c3dd53f
BLAKE2b-256 10b7d558054d4ab44275726facba6189432ae16520b5961a49f91b063b856860

See more details on using hashes here.

File details

Details for the file django_react_kit-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for django_react_kit-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c5a53335edb463c88c030074c9363aa5fcd47c1eae576f74ca4513c7c4da0264
MD5 fdfa2fe8b510ca3791809989a3178026
BLAKE2b-256 1bb057389a8cb3980ac2840782e32addc9a93aefdaa23056ff34cbfe6075189e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page