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
- Build the frontend for production:
python manage.py reactbuild --production
-
Ensure Node.js is available on your server
-
Configure your web server (nginx/Apache) to serve static files
-
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
- Documentation: Read the full docs
- Issues: Report bugs or request features
- Discussions: Join our community discussions
๐ 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file django_react_kit-1.0.2.tar.gz.
File metadata
- Download URL: django_react_kit-1.0.2.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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
45b84e5787c9e939deab7ce568e94f709c9af1ddc2b9a494c251bc69bc958fc9
|
|
| MD5 |
02d8af01ed4d0539f29708b5994e78b6
|
|
| BLAKE2b-256 |
0dbf6417d6b46f57561e372924336f7975270fac8140c9bd5fc53c5045ec7dd4
|
File details
Details for the file django_react_kit-1.0.2-py3-none-any.whl.
File metadata
- Download URL: django_react_kit-1.0.2-py3-none-any.whl
- Upload date:
- Size: 16.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c1fc1b2153dda2738e49917e51e7176f3fb611f27bc07823bb04cf0dca7a6768
|
|
| MD5 |
9c6fe9e56870cdb6d57ff19267f6ffec
|
|
| BLAKE2b-256 |
338e0318d37a5cd118baa84a4d5a33324b185eb8295ea04d4752606e6fe04050
|