django-cf is a Python package that seamlessly integrates your Django applications with various Cloudflare services. Utilize the power of Cloudflare's global network for your Django projects.
pip install django-cfNote on Cloudflare Workers Plan: This package requires a Cloudflare Workers Paid Plan for production use. Django loads many modules which can exceed the CPU time limits included in free accounts. However, if you're interested in experimenting on the free account, feel free to try it out! If you manage to get it working on the free plan, please open an issue describing your setup so other users can benefit from your solution.
This package provides integration with the following Cloudflare products:
- Cloudflare Workers: Run your Django application on Cloudflare's serverless compute platform.
- Cloudflare D1: Use Cloudflare's serverless SQL database as a backend for your Django application.
- Cloudflare Durable Objects: Leverage stateful objects for applications requiring persistent state within Cloudflare Workers.
- Cloudflare Access Authentication: Seamless authentication middleware for Cloudflare Access protected applications.
Use Cloudflare D1, a serverless SQL database, as your Django application's database.
Important:
- Transactions are disabled for all D1 database engines. Every query is committed immediately.
- The D1 backend has some limitations compared to traditional SQLite or other SQL databases. Many advanced ORM features or direct SQL functions (especially those used in Django Admin) might not be fully supported. Refer to the "Limitations" section.
Configuration:
-
wrangler.jsonc(orwrangler.toml): -
Worker Entrypoint (
src/index.py):from workers import WorkerEntrypoint from django_cf import DjangoCF class Default(DjangoCF, WorkerEntrypoint): async def get_app(self): from app.wsgi import application return application
-
Django Settings (
settings.py):DATABASES = { 'default': { 'ENGINE': 'django_cf.db.backends.d1', # 'CLOUDFLARE_BINDING' should match the binding name in your wrangler.jsonc 'CLOUDFLARE_BINDING': 'DB', } }
For a complete working example with full configuration and management endpoints, see the D1 template.
Utilize Durable Objects for stateful data persistence directly within your Cloudflare Workers. This is useful for applications requiring low-latency access to state associated with specific objects or instances.
Important:
- Transactions are disabled for Durable Objects. All queries are committed immediately, and rollbacks are not available.
- Durable Objects offer a unique model for state. Understand its consistency and scalability characteristics before implementing.
Configuration:
-
wrangler.jsonc(orwrangler.toml): Define your Durable Object class and binding.{ "durable_objects": { "bindings": [ { "name": "DO_STORAGE", "class_name": "DjangoDO" } ] }, "migrations": [ { "tag": "v1", "new_sqlite_classes": ["DjangoDO"] } ] } -
Worker Entrypoint (
src/index.py):from workers import DurableObject, WorkerEntrypoint from django_cf import DjangoCFDurableObject class DjangoDO(DjangoCFDurableObject, DurableObject): def get_app(self): from app.wsgi import application return application class Default(WorkerEntrypoint): async def fetch(self, request): # Route requests to a DO instance id = self.env.DO_STORAGE.idFromName("singleton_instance") obj = self.env.DO_STORAGE.get(id) return await obj.fetch(request)
-
Django Settings (
settings.py):DATABASES = { 'default': { 'ENGINE': 'django_cf.db.backends.do', } }
For a complete working example with full configuration and management endpoints, see the Durable Objects template.
Complete, production-ready examples are available in the templates/ directory:
- D1 Template - Django on Cloudflare Workers with D1 database
- Durable Objects Template - Django on Cloudflare Workers with Durable Objects
Each template includes:
- Pre-configured
wrangler.toml(orwrangler.jsonc) - Worker entrypoint setup
- Django settings configured for the respective backend
- Management command endpoints for migrations and admin creation
- Complete deployment instructions
Seamless authentication middleware for Cloudflare Access protected applications. The middleware is implemented using only Python standard library modules - no external dependencies required!
This middleware works on both self-hosted Django applications and Django hosted on Cloudflare Workers.
# settings.py
INSTALLED_APPS = [
# ... your other apps
'django_cf',
]Add the middleware to your Django settings:
# settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware', # Must be before CloudflareAccessMiddleware
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django_cf.middleware.CloudflareAccessMiddleware',
# ... other middleware (should be placed appropriately in your middleware stack)
]Add the required settings to your Django configuration:
# settings.py
# Required settings (at least one must be provided)
CLOUDFLARE_ACCESS_AUD = 'your-application-audience-tag' # Optional if team name is provided
CLOUDFLARE_ACCESS_TEAM_NAME = 'yourteam' # Optional if AUD is provided
# Optional settings
CLOUDFLARE_ACCESS_EXEMPT_PATHS = [
'/health/',
'/api/public/',
'/admin/login/', # If you want to keep Django admin login
]
CLOUDFLARE_ACCESS_CACHE_TIMEOUT = 3600 # Cache timeout for public keys (seconds)You must provide at least one of the following settings:
Your Cloudflare Access Application Audience (AUD) tag. You can find this in your Cloudflare Zero Trust dashboard:
- Go to Access → Applications
- Select your application
- Copy the "Application Audience (AUD) Tag"
When to use: Provide this if you want strict audience validation or if you have multiple applications with the same team.
Your Cloudflare team name (the subdomain part of your team domain). For example, if your team domain is mycompany.cloudflareaccess.com, then your team name is mycompany.
When to use: Provide this if you want simpler configuration or if you only have one application per team.
You can configure the middleware in three ways:
-
Both AUD and Team Name (Recommended for production):
CLOUDFLARE_ACCESS_AUD = 'your-application-audience-tag' CLOUDFLARE_ACCESS_TEAM_NAME = 'yourteam'
-
Only AUD (Team name extracted from JWT):
CLOUDFLARE_ACCESS_AUD = 'your-application-audience-tag'
-
Only Team Name (AUD validated but not enforced):
CLOUDFLARE_ACCESS_TEAM_NAME = 'yourteam'
Default: []
List of URL paths that should be exempt from Cloudflare Access authentication. Useful for:
- Health check endpoints
- Public API endpoints
- Webhooks
- Static file serving (if not handled by your web server)
Example:
CLOUDFLARE_ACCESS_EXEMPT_PATHS = [
'/health/',
'/api/public/',
'/webhooks/',
'/static/', # If serving static files through Django
]Default: 3600 (1 hour)
How long to cache Cloudflare's public keys (in seconds). Cloudflare rotates these keys periodically, so caching reduces API calls while ensuring fresh keys are fetched when needed.
- Request Processing: For each incoming request, the middleware checks if the path is exempt from authentication
- JWT Extraction: Extracts the JWT token from:
CF-Access-Jwt-Assertionheader (preferred)CF_Authorizationcookie (fallback)
- Team Discovery: If team name is not configured, extracts it from the JWT's issuer claim
- Public Key Retrieval: Fetches Cloudflare's public keys from the team's certs endpoint
- Token Validation: Validates the JWT against Cloudflare's public keys:
- Validates token signature and expiration
- Validates audience (AUD) if configured
- User Management:
- Extracts email and name from JWT claims
- Creates new Django user if doesn't exist
- Updates existing user's name if changed
- Logs the user into Django session
- Response: Proceeds with the request if authentication succeeds, returns 401 if it fails
When a user authenticates for the first time:
- Username is set to the user's email address
- Email is extracted from JWT
emailclaim - Name is split into first_name and last_name from JWT
nameclaim - User is created with
is_active=True
For existing users:
- Name is updated if it has changed in Cloudflare
- User is automatically logged in
- All JWT tokens are validated against Cloudflare's public keys
- Tokens are checked for expiration
- Audience (AUD) is validated to ensure tokens are for your application
- Public keys are cached to reduce API calls to Cloudflare
- Cache keys are scoped to your team name
- Failed key fetches are logged but don't crash the application
- Authentication failures return 401 responses
- Server errors return 500 responses
- All errors are logged for debugging
The middleware uses Django's logging system with logger name django_cf.middleware. To see debug information:
# settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django_cf.middleware': {
'handlers': ['console'],
'level': 'INFO',
'propagate': True,
},
},
}Cause: JWT token is missing, invalid, or expired.
Solutions:
- Ensure your application is behind Cloudflare Access
- Check that users are properly authenticated with Cloudflare Access
- If using
CLOUDFLARE_ACCESS_AUD, verify it matches your application's AUD tag - If using
CLOUDFLARE_ACCESS_TEAM_NAME, check that it's correct - Review middleware logs for specific validation errors
Cause: Unable to fetch Cloudflare public keys or other configuration issues.
Solutions:
- Verify your team name is correct (if using
CLOUDFLARE_ACCESS_TEAM_NAME) - Check network connectivity to Cloudflare
- Review logs for specific error messages
- If using only AUD, ensure the JWT contains a valid issuer claim
Cause: Missing email claim in JWT or database issues.
Solutions:
- Check that your Cloudflare Access application is configured to include email in JWT
- Verify Django database migrations are up to date
- Check Django user model permissions
If you need custom user creation logic, you can subclass the middleware:
from django_cf.middleware import CloudflareAccessMiddleware
from django.contrib.auth import get_user_model
User = get_user_model()
class CustomCloudflareAccessMiddleware(CloudflareAccessMiddleware):
def _get_or_create_user(self, email, name):
# Your custom user creation logic here
user, created = User.objects.get_or_create(
email=email,
defaults={
'username': email,
'first_name': name.split(' ')[0] if name else '',
'last_name': ' '.join(name.split(' ')[1:]) if name else '',
'is_active': True,
'is_staff': email.endswith('@yourcompany.com'), # Custom logic
}
)
return userIf you have multiple Cloudflare Access applications, you can configure different middleware instances or use environment-specific settings.
When developing applications with this middleware, you may want to disable it in certain environments:
# settings.py
if DEBUG and not os.getenv('ENABLE_CF_ACCESS'):
# Remove CloudflareAccessMiddleware from MIDDLEWARE list
MIDDLEWARE = [m for m in MIDDLEWARE if 'CloudflareAccessMiddleware' not in m]For local development without Cloudflare Access:
- Set exempt paths to include your development URLs
- Use Django's built-in authentication for local testing
- Consider using environment variables to toggle the middleware
- D1 Database:
- Transactions are disabled for all D1 engines (Binding and API). All queries are final, and rollbacks are not available.
- When using the D1 API engine, queries can be slower compared to the D1 Binding engine due to the overhead of HTTP requests.
- A number of Django ORM features, particularly those relying on specific SQL functions (e.g., some used by the Django Admin), may not work as expected or at all. Django Admin functionality will be limited.
- Always refer to the official Django limitations for SQLite databases, as D1 is SQLite-compatible but has its own serverless characteristics.
- Durable Objects:
- Transactions are disabled. All queries are final, and rollbacks are not available.
- While powerful for stateful serverless applications, ensure you understand the consistency model and potential data storage costs associated with Durable Objects.
See DEVELOPMENT.md for details on setting up a development environment and contributing to django-cf.
We welcome contributions! Please see our contributing guidelines and feel free to submit issues and pull requests.
For issues and questions:
- Check the troubleshooting section above
- Review Cloudflare Access documentation
- Submit an issue on GitHub with detailed error logs and configuration (remove sensitive information)
This project is licensed under the MIT License. See the LICENSE file for details.
For complete, working examples of Django projects on Cloudflare Workers, refer to the templates in the templates/ directory.
{ "d1_databases": [ { "binding": "DB", "database_name": "my-django-db", "database_id": "your-d1-database-id" } ] }