# FastAPI Device ID
[](https://pypi.org/project/fastapi-device-id/)
[](https://pypi.org/project/fastapi-device-id/)
[](https://github.com/ideatives/fastapi-device-id/actions)
[](https://github.com/ideatives/fastapi-device-id/blob/main/LICENSE)
> **Track devices across sessions without user registration. Perfect for analytics, rate limiting, and A/B testing.**
Drop-in device tracking for FastAPI apps. Get persistent device IDs without user accounts, databases, or privacy concerns.
## Why FastAPI Device ID?
### The Problem
Modern web applications often need to:
- **Track user behavior** across sessions without requiring login
- **Implement rate limiting** per device to prevent abuse
- **Provide consistent A/B testing** experiences
- **Analyze usage patterns** and user journeys
- **Differentiate between devices** for security or UX purposes
Traditional solutions are either too complex (full user accounts), privacy-invasive (fingerprinting), or unreliable (IP addresses change, shared networks).
### The Solution
FastAPI Device ID provides a **privacy-friendly middle ground**:
✅ **No personal data required** - Just a unique identifier per browser
✅ **Persistent across sessions** - Survives browser restarts
✅ **Secure by default** - HTTP-only cookies with CSRF protection
✅ **Scalable** - Works across multiple server instances
✅ **Compliant** - Respects user privacy, no tracking across domains
### When to Use
Perfect for applications that need:
- **Anonymous analytics** without user accounts
- **Rate limiting** by device rather than IP
- **Session continuity** across page reloads
- **A/B testing** with consistent user experiences
- **Fraud prevention** through device recognition
- **Usage quotas** for anonymous API access
### When NOT to Use
Consider alternatives if you need:
- **Cross-domain tracking** (this is single-domain only)
- **User authentication** (use proper auth systems instead)
- **Long-term user identification** (users can clear cookies)
- **Foolproof uniqueness** (sophisticated users can bypass)
## Features
- 🔒 **Secure by default**: HTTP-only, secure, and SameSite cookies
- 🆔 **Modern UUID**: Uses UUID7 (time-ordered) with UUID4 fallback for older Python versions
- 📦 **Zero dependencies**: Only requires FastAPI/Starlette (which you already have)
- ⚙️ **Highly configurable**: Customize cookie names, expiration, and security settings
- 🪶 **Lightweight**: Minimal overhead with pluggable architecture
- 🔧 **Type safe**: Full type hints with dependency injection support
- 🔌 **Pluggable**: Custom ID generators and security strategies
- 🛡️ **Multiple security strategies**: Plaintext, JWT, and AES encryption support
- ⚡ **Performance optimized**: Constant-time comparisons and efficient encoding
- 🌐 **Production ready**: Distributed deployment support with consistent encryption
## 🚀 Quick Start
### Installation
```bash
pip install fastapi-device-id
```
**In production in 2 minutes:**
1. Add the middleware: `app.add_middleware(DeviceMiddleware)`
2. Use the dependency: `async def handler(device_id: DeviceId):`
3. Start tracking: `analytics.track(device_id, event)`
### Basic Usage
```python
from fastapi import FastAPI
from fastapi_device_id import DeviceMiddleware, DeviceId
app = FastAPI()
# Add the middleware
app.add_middleware(DeviceMiddleware)
@app.get("/")
async def read_root(device_id: DeviceId):
# This device_id is automatically persistent across browser sessions
# No database setup required!
return {"message": f"Welcome back, device {device_id}"}
@app.get("/analytics")
async def track_visit(device_id: DeviceId):
# Log analytics, track user behavior, etc.
print(f"Device {device_id} visited /analytics")
return {"status": "visit tracked"}
```
### Custom Configuration
```python
from fastapi import FastAPI
from fastapi_device_id import DeviceMiddleware
app = FastAPI()
# Customize the middleware
app.add_middleware(
DeviceMiddleware,
cookie_name="my_device_id", # Custom cookie name
cookie_max_age=30 * 24 * 60 * 60, # 30 days instead of 1 year
cookie_secure=False, # Allow HTTP in development
cookie_samesite="strict", # Stricter cookie policy
)
```
### Custom ID Generator
```python
import secrets
from fastapi import FastAPI
from fastapi_device_id import DeviceMiddleware
def custom_id_generator() -> str:
"""Generate a custom device ID."""
return f"device_{secrets.token_hex(16)}"
app = FastAPI()
app.add_middleware(
DeviceMiddleware,
id_generator=custom_id_generator,
)
```
### Security Strategies
FastAPI Device ID supports multiple security strategies for device ID storage:
#### Plaintext Strategy (Default)
```python
from fastapi_device_id import DeviceMiddleware, PlaintextStrategy
app.add_middleware(
DeviceMiddleware,
security_strategy=PlaintextStrategy(),
)
```
#### JWT Strategy
Provides tamper detection with cryptographic signatures:
```python
from fastapi_device_id import DeviceMiddleware, JWTStrategy
# JWT with signature verification
app.add_middleware(
DeviceMiddleware,
security_strategy=JWTStrategy(
secret="your-secret-key",
algorithm="HS256",
expiration_hours=24 # Optional expiration
),
)
```
#### Encrypted Strategy
Provides confidentiality - device ID is hidden from client:
```python
from fastapi_device_id import DeviceMiddleware, EncryptedStrategy
# AES encryption with Fernet (recommended)
app.add_middleware(
DeviceMiddleware,
security_strategy=EncryptedStrategy(
key="your-encryption-key",
algorithm="fernet" # or "aes-256-gcm", "aes-128-gcm"
),
)
# Production example with environment variable
import os
app.add_middleware(
DeviceMiddleware,
security_strategy=EncryptedStrategy(
key=os.environ["DEVICE_ID_ENCRYPTION_KEY"],
algorithm="fernet"
),
)
```
#### Security Strategy Comparison
| Strategy | Confidentiality | Integrity | Performance | Use Case |
|----------|----------------|-----------|-------------|----------|
| Plaintext | ❌ | ❌ | ⚡ Fastest | Development, non-sensitive |
| JWT | ❌ | ✅ | 🟨 Medium | Tamper detection needed |
| Encrypted | ✅ | ✅ | 🟨 Medium | Production, sensitive data |
## API Reference
### DeviceMiddleware
The main middleware class that handles device identification.
#### Parameters
- **`cookie_name`** (`str`, default: `"device_id"`): Name of the cookie to store the device ID
- **`cookie_max_age`** (`int`, default: `365 * 24 * 60 * 60`): Cookie expiration time in seconds (1 year)
- **`cookie_expires`** (`str | None`, default: `None`): Cookie expiration date string
- **`cookie_path`** (`str`, default: `"/"`): Cookie path
- **`cookie_domain`** (`str | None`, default: `None`): Cookie domain
- **`cookie_secure`** (`bool`, default: `True`): Whether the cookie should only be sent over HTTPS
- **`cookie_httponly`** (`bool`, default: `True`): Whether the cookie should be inaccessible to JavaScript
- **`cookie_samesite`** (`str`, default: `"lax"`): SameSite policy (`"strict"`, `"lax"`, or `"none"`)
- **`id_generator`** (`Callable[[], str]`, default: `default_id_generator`): Function to generate device IDs
- **`security_strategy`** (`DeviceIDSecurityStrategy`, default: `PlaintextStrategy()`): Security strategy for encoding device IDs
### DeviceId Type
A FastAPI dependency that extracts the device ID from the request:
```python
from fastapi_device_id import DeviceId
@app.get("/my-endpoint")
async def my_handler(device_id: DeviceId):
# device_id is automatically extracted and typed as str
return {"device_id": device_id}
```
### get_device_id Function
Direct function to extract device ID from a request:
```python
from fastapi import Request
from fastapi_device_id import get_device_id
@app.get("/manual")
async def manual_extraction(request: Request):
device_id = get_device_id(request)
return {"device_id": device_id}
```
### compare_device_ids Function
Secure constant-time comparison of device IDs to prevent timing attacks:
```python
from fastapi_device_id import compare_device_ids
@app.get("/secure-compare")
async def secure_comparison(device_id: DeviceId, stored_id: str):
# ❌ VULNERABLE to timing attacks
# if device_id == stored_id:
# ✅ SECURE constant-time comparison
if compare_device_ids(device_id, stored_id):
return {"access": "granted"}
return {"access": "denied"}
```
## Performance
- **Zero dependencies** beyond FastAPI/Starlette
- **<1ms overhead** per request
- **Memory efficient**: No server-side storage required
- **Scales horizontally**: Stateless design works across instances
- **Cookie-based**: Works with CDNs and load balancers
## Use Cases
### Analytics and Tracking
```python
@app.get("/track-page-view")
async def track_page_view(device_id: DeviceId, page: str):
# Store page view with device ID
analytics.track_page_view(device_id, page)
return {"status": "tracked"}
```
### A/B Testing
```python
@app.get("/feature")
async def get_feature_flag(device_id: DeviceId):
# Consistent A/B testing based on device ID
variant = "A" if int(device_id.replace("-", ""), 16) % 2 else "B"
return {"variant": variant}
```
### Rate Limiting
```python
from collections import defaultdict
from time import time
rate_limits = defaultdict(list)
@app.get("/api/data")
async def get_data(device_id: DeviceId):
now = time()
device_requests = rate_limits[device_id]
# Clean old requests (1 hour window)
device_requests[:] = [req_time for req_time in device_requests if now - req_time < 3600]
if len(device_requests) >= 100: # 100 requests per hour
return {"error": "Rate limit exceeded"}
device_requests.append(now)
return {"data": "your data here"}
```
## Common Patterns
### Anonymous User Analytics
```python
from fastapi_device_id import DeviceId
import logging
analytics_logger = logging.getLogger("analytics")
@app.get("/page/{page_name}")
async def track_page_view(page_name: str, device_id: DeviceId):
analytics_logger.info(f"Device {device_id} viewed {page_name}")
return {"content": f"Welcome to {page_name}"}
@app.post("/event")
async def track_custom_event(event: dict, device_id: DeviceId):
event["device_id"] = device_id
analytics_logger.info(f"Custom event: {event}")
return {"status": "tracked"}
```
### Shopping Cart Persistence
```python
from typing import Dict, List
carts: Dict[str, List[dict]] = {}
@app.post("/cart/add")
async def add_to_cart(item: dict, device_id: DeviceId):
if device_id not in carts:
carts[device_id] = []
carts[device_id].append(item)
return {"cart_size": len(carts[device_id])}
@app.get("/cart")
async def get_cart(device_id: DeviceId):
return {"items": carts.get(device_id, [])}
```
### Feature Flag Management
```python
import hashlib
@app.get("/feature/{feature_name}")
async def get_feature_flag(feature_name: str, device_id: DeviceId):
# Consistent feature assignment based on device ID
hash_input = f"{feature_name}:{device_id}"
hash_value = int(hashlib.md5(hash_input.encode()).hexdigest()[:8], 16)
enabled = hash_value % 100 < 50 # 50% rollout
return {"feature": feature_name, "enabled": enabled}
```
## Configuration Examples
### Development Setup
```python
# Relaxed settings for local development
app.add_middleware(
DeviceMiddleware,
cookie_secure=False, # Allow HTTP
cookie_samesite="lax", # Relaxed policy
security_strategy=PlaintextStrategy(), # No encryption overhead
)
```
### Production Setup
```python
import os
from fastapi_device_id import EncryptedStrategy
# Strict security for production
app.add_middleware(
DeviceMiddleware,
cookie_secure=True, # HTTPS only
cookie_httponly=True, # No JavaScript access
cookie_samesite="strict", # Strict policy
security_strategy=EncryptedStrategy(
key=os.environ["DEVICE_ID_ENCRYPTION_KEY"],
algorithm="fernet"
),
)
```
### Short-lived Sessions with JWT
```python
from fastapi_device_id import JWTStrategy
# JWT tokens that expire after 24 hours
app.add_middleware(
DeviceMiddleware,
security_strategy=JWTStrategy(
secret="your-jwt-secret",
expiration_hours=24
),
)
```
### High-Security Setup
```python
import os
from fastapi_device_id import EncryptedStrategy
# Maximum security configuration
app.add_middleware(
DeviceMiddleware,
cookie_secure=True,
cookie_httponly=True,
cookie_samesite="strict",
cookie_max_age=7 * 24 * 60 * 60, # 1 week
security_strategy=EncryptedStrategy(
key=os.environ["DEVICE_ID_ENCRYPTION_KEY"],
algorithm="aes-256-gcm", # Strong encryption
iterations=200000, # Higher security
),
)
```
## Requirements
- Python 3.8+
- FastAPI 0.68.0+
- Starlette 0.14.0+
### Optional Dependencies
For JWT strategy support:
```bash
pip install "fastapi-device-id[jwt]"
```
For encryption strategy support:
```bash
pip install "fastapi-device-id[crypto]"
```
For development:
```bash
pip install "fastapi-device-id[dev]"
```
For all features:
```bash
pip install "fastapi-device-id[jwt,crypto,dev]"
```
## Production Checklist
Before deploying to production, ensure:
- [ ] **Security Strategy**: Use `EncryptedStrategy` or `JWTStrategy` instead of `PlaintextStrategy`
- [ ] **Environment Variables**: Store encryption keys in `os.environ`, never in code
- [ ] **Cookie Security**: Set `cookie_secure=True` for HTTPS-only cookies
- [ ] **SameSite Policy**: Use `cookie_samesite="strict"` for maximum security
- [ ] **Key Rotation**: Plan for periodic encryption key rotation
- [ ] **Monitoring**: Log device ID operations for debugging
- [ ] **Privacy Policy**: Update your privacy policy to mention device tracking
- [ ] **GDPR Compliance**: Implement cookie consent if required in your jurisdiction
### Example Production Configuration
```python
import os
from fastapi_device_id import DeviceMiddleware, EncryptedStrategy
app.add_middleware(
DeviceMiddleware,
cookie_secure=True,
cookie_httponly=True,
cookie_samesite="strict",
security_strategy=EncryptedStrategy(
key=os.environ["DEVICE_ID_ENCRYPTION_KEY"],
algorithm="fernet"
),
)
```
## Contributing
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
### Development Setup
```bash
# Clone the repository
git clone https://github.com/ideatives/fastapi-device-id.git
cd fastapi-device-id
# Install development dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Format code
black src tests
ruff --fix src tests
# Type checking
mypy src
```
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Changelog
See [CHANGELOG.md](CHANGELOG.md) for version history.
## Security
For security issues, please see our [Security Policy](SECURITY.md).
Raw data
{
"_id": null,
"home_page": null,
"name": "fastapi-device-id",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": "Ideatives <info@ideatives.com>",
"keywords": "a-b-testing, analytics, anonymous-tracking, cookie, device-tracking, fastapi, middleware, rate-limiting, session-management, starlette, uuid, web-analytics",
"author": null,
"author_email": "Ideatives <info@ideatives.com>",
"download_url": "https://files.pythonhosted.org/packages/a3/27/9618ad9ce64032beceb05c0e34bbc3a59092c629511b18e32a41097d8082/fastapi_device_id-0.1.0.tar.gz",
"platform": null,
"description": "# FastAPI Device ID\n\n[](https://pypi.org/project/fastapi-device-id/)\n[](https://pypi.org/project/fastapi-device-id/)\n[](https://github.com/ideatives/fastapi-device-id/actions)\n[](https://github.com/ideatives/fastapi-device-id/blob/main/LICENSE)\n\n> **Track devices across sessions without user registration. Perfect for analytics, rate limiting, and A/B testing.**\n\nDrop-in device tracking for FastAPI apps. Get persistent device IDs without user accounts, databases, or privacy concerns.\n\n## Why FastAPI Device ID?\n\n### The Problem\nModern web applications often need to:\n- **Track user behavior** across sessions without requiring login\n- **Implement rate limiting** per device to prevent abuse\n- **Provide consistent A/B testing** experiences\n- **Analyze usage patterns** and user journeys\n- **Differentiate between devices** for security or UX purposes\n\nTraditional solutions are either too complex (full user accounts), privacy-invasive (fingerprinting), or unreliable (IP addresses change, shared networks).\n\n### The Solution\nFastAPI Device ID provides a **privacy-friendly middle ground**:\n\n\u2705 **No personal data required** - Just a unique identifier per browser \n\u2705 **Persistent across sessions** - Survives browser restarts \n\u2705 **Secure by default** - HTTP-only cookies with CSRF protection \n\u2705 **Scalable** - Works across multiple server instances \n\u2705 **Compliant** - Respects user privacy, no tracking across domains \n\n### When to Use\nPerfect for applications that need:\n- **Anonymous analytics** without user accounts\n- **Rate limiting** by device rather than IP\n- **Session continuity** across page reloads\n- **A/B testing** with consistent user experiences\n- **Fraud prevention** through device recognition\n- **Usage quotas** for anonymous API access\n\n### When NOT to Use\nConsider alternatives if you need:\n- **Cross-domain tracking** (this is single-domain only)\n- **User authentication** (use proper auth systems instead)\n- **Long-term user identification** (users can clear cookies)\n- **Foolproof uniqueness** (sophisticated users can bypass)\n\n## Features\n\n- \ud83d\udd12 **Secure by default**: HTTP-only, secure, and SameSite cookies\n- \ud83c\udd94 **Modern UUID**: Uses UUID7 (time-ordered) with UUID4 fallback for older Python versions\n- \ud83d\udce6 **Zero dependencies**: Only requires FastAPI/Starlette (which you already have)\n- \u2699\ufe0f **Highly configurable**: Customize cookie names, expiration, and security settings\n- \ud83e\udeb6 **Lightweight**: Minimal overhead with pluggable architecture\n- \ud83d\udd27 **Type safe**: Full type hints with dependency injection support\n- \ud83d\udd0c **Pluggable**: Custom ID generators and security strategies\n- \ud83d\udee1\ufe0f **Multiple security strategies**: Plaintext, JWT, and AES encryption support\n- \u26a1 **Performance optimized**: Constant-time comparisons and efficient encoding\n- \ud83c\udf10 **Production ready**: Distributed deployment support with consistent encryption\n\n## \ud83d\ude80 Quick Start\n\n### Installation\n\n```bash\npip install fastapi-device-id\n```\n\n**In production in 2 minutes:**\n1. Add the middleware: `app.add_middleware(DeviceMiddleware)`\n2. Use the dependency: `async def handler(device_id: DeviceId):`\n3. Start tracking: `analytics.track(device_id, event)`\n\n### Basic Usage\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_device_id import DeviceMiddleware, DeviceId\n\napp = FastAPI()\n\n# Add the middleware\napp.add_middleware(DeviceMiddleware)\n\n@app.get(\"/\")\nasync def read_root(device_id: DeviceId):\n # This device_id is automatically persistent across browser sessions\n # No database setup required!\n return {\"message\": f\"Welcome back, device {device_id}\"}\n\n@app.get(\"/analytics\")\nasync def track_visit(device_id: DeviceId):\n # Log analytics, track user behavior, etc.\n print(f\"Device {device_id} visited /analytics\")\n return {\"status\": \"visit tracked\"}\n```\n\n### Custom Configuration\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_device_id import DeviceMiddleware\n\napp = FastAPI()\n\n# Customize the middleware\napp.add_middleware(\n DeviceMiddleware,\n cookie_name=\"my_device_id\", # Custom cookie name\n cookie_max_age=30 * 24 * 60 * 60, # 30 days instead of 1 year\n cookie_secure=False, # Allow HTTP in development\n cookie_samesite=\"strict\", # Stricter cookie policy\n)\n```\n\n### Custom ID Generator\n\n```python\nimport secrets\nfrom fastapi import FastAPI\nfrom fastapi_device_id import DeviceMiddleware\n\ndef custom_id_generator() -> str:\n \"\"\"Generate a custom device ID.\"\"\"\n return f\"device_{secrets.token_hex(16)}\"\n\napp = FastAPI()\napp.add_middleware(\n DeviceMiddleware,\n id_generator=custom_id_generator,\n)\n```\n\n### Security Strategies\n\nFastAPI Device ID supports multiple security strategies for device ID storage:\n\n#### Plaintext Strategy (Default)\n\n```python\nfrom fastapi_device_id import DeviceMiddleware, PlaintextStrategy\n\napp.add_middleware(\n DeviceMiddleware,\n security_strategy=PlaintextStrategy(),\n)\n```\n\n#### JWT Strategy\n\nProvides tamper detection with cryptographic signatures:\n\n```python\nfrom fastapi_device_id import DeviceMiddleware, JWTStrategy\n\n# JWT with signature verification\napp.add_middleware(\n DeviceMiddleware,\n security_strategy=JWTStrategy(\n secret=\"your-secret-key\",\n algorithm=\"HS256\",\n expiration_hours=24 # Optional expiration\n ),\n)\n```\n\n#### Encrypted Strategy\n\nProvides confidentiality - device ID is hidden from client:\n\n```python\nfrom fastapi_device_id import DeviceMiddleware, EncryptedStrategy\n\n# AES encryption with Fernet (recommended)\napp.add_middleware(\n DeviceMiddleware,\n security_strategy=EncryptedStrategy(\n key=\"your-encryption-key\",\n algorithm=\"fernet\" # or \"aes-256-gcm\", \"aes-128-gcm\"\n ),\n)\n\n# Production example with environment variable\nimport os\napp.add_middleware(\n DeviceMiddleware,\n security_strategy=EncryptedStrategy(\n key=os.environ[\"DEVICE_ID_ENCRYPTION_KEY\"],\n algorithm=\"fernet\"\n ),\n)\n```\n\n#### Security Strategy Comparison\n\n| Strategy | Confidentiality | Integrity | Performance | Use Case |\n|----------|----------------|-----------|-------------|----------|\n| Plaintext | \u274c | \u274c | \u26a1 Fastest | Development, non-sensitive |\n| JWT | \u274c | \u2705 | \ud83d\udfe8 Medium | Tamper detection needed |\n| Encrypted | \u2705 | \u2705 | \ud83d\udfe8 Medium | Production, sensitive data |\n\n## API Reference\n\n### DeviceMiddleware\n\nThe main middleware class that handles device identification.\n\n#### Parameters\n\n- **`cookie_name`** (`str`, default: `\"device_id\"`): Name of the cookie to store the device ID\n- **`cookie_max_age`** (`int`, default: `365 * 24 * 60 * 60`): Cookie expiration time in seconds (1 year)\n- **`cookie_expires`** (`str | None`, default: `None`): Cookie expiration date string\n- **`cookie_path`** (`str`, default: `\"/\"`): Cookie path\n- **`cookie_domain`** (`str | None`, default: `None`): Cookie domain\n- **`cookie_secure`** (`bool`, default: `True`): Whether the cookie should only be sent over HTTPS\n- **`cookie_httponly`** (`bool`, default: `True`): Whether the cookie should be inaccessible to JavaScript\n- **`cookie_samesite`** (`str`, default: `\"lax\"`): SameSite policy (`\"strict\"`, `\"lax\"`, or `\"none\"`)\n- **`id_generator`** (`Callable[[], str]`, default: `default_id_generator`): Function to generate device IDs\n- **`security_strategy`** (`DeviceIDSecurityStrategy`, default: `PlaintextStrategy()`): Security strategy for encoding device IDs\n\n### DeviceId Type\n\nA FastAPI dependency that extracts the device ID from the request:\n\n```python\nfrom fastapi_device_id import DeviceId\n\n@app.get(\"/my-endpoint\")\nasync def my_handler(device_id: DeviceId):\n # device_id is automatically extracted and typed as str\n return {\"device_id\": device_id}\n```\n\n### get_device_id Function\n\nDirect function to extract device ID from a request:\n\n```python\nfrom fastapi import Request\nfrom fastapi_device_id import get_device_id\n\n@app.get(\"/manual\")\nasync def manual_extraction(request: Request):\n device_id = get_device_id(request)\n return {\"device_id\": device_id}\n```\n\n### compare_device_ids Function\n\nSecure constant-time comparison of device IDs to prevent timing attacks:\n\n```python\nfrom fastapi_device_id import compare_device_ids\n\n@app.get(\"/secure-compare\")\nasync def secure_comparison(device_id: DeviceId, stored_id: str):\n # \u274c VULNERABLE to timing attacks\n # if device_id == stored_id:\n \n # \u2705 SECURE constant-time comparison\n if compare_device_ids(device_id, stored_id):\n return {\"access\": \"granted\"}\n return {\"access\": \"denied\"}\n```\n\n## Performance\n\n- **Zero dependencies** beyond FastAPI/Starlette\n- **<1ms overhead** per request\n- **Memory efficient**: No server-side storage required\n- **Scales horizontally**: Stateless design works across instances\n- **Cookie-based**: Works with CDNs and load balancers\n\n## Use Cases\n\n### Analytics and Tracking\n\n```python\n@app.get(\"/track-page-view\")\nasync def track_page_view(device_id: DeviceId, page: str):\n # Store page view with device ID\n analytics.track_page_view(device_id, page)\n return {\"status\": \"tracked\"}\n```\n\n### A/B Testing\n\n```python\n@app.get(\"/feature\")\nasync def get_feature_flag(device_id: DeviceId):\n # Consistent A/B testing based on device ID\n variant = \"A\" if int(device_id.replace(\"-\", \"\"), 16) % 2 else \"B\"\n return {\"variant\": variant}\n```\n\n### Rate Limiting\n\n```python\nfrom collections import defaultdict\nfrom time import time\n\nrate_limits = defaultdict(list)\n\n@app.get(\"/api/data\")\nasync def get_data(device_id: DeviceId):\n now = time()\n device_requests = rate_limits[device_id]\n \n # Clean old requests (1 hour window)\n device_requests[:] = [req_time for req_time in device_requests if now - req_time < 3600]\n \n if len(device_requests) >= 100: # 100 requests per hour\n return {\"error\": \"Rate limit exceeded\"}\n \n device_requests.append(now)\n return {\"data\": \"your data here\"}\n```\n\n## Common Patterns\n\n### Anonymous User Analytics\n\n```python\nfrom fastapi_device_id import DeviceId\nimport logging\n\nanalytics_logger = logging.getLogger(\"analytics\")\n\n@app.get(\"/page/{page_name}\")\nasync def track_page_view(page_name: str, device_id: DeviceId):\n analytics_logger.info(f\"Device {device_id} viewed {page_name}\")\n return {\"content\": f\"Welcome to {page_name}\"}\n\n@app.post(\"/event\")\nasync def track_custom_event(event: dict, device_id: DeviceId):\n event[\"device_id\"] = device_id\n analytics_logger.info(f\"Custom event: {event}\")\n return {\"status\": \"tracked\"}\n```\n\n### Shopping Cart Persistence\n\n```python\nfrom typing import Dict, List\ncarts: Dict[str, List[dict]] = {}\n\n@app.post(\"/cart/add\")\nasync def add_to_cart(item: dict, device_id: DeviceId):\n if device_id not in carts:\n carts[device_id] = []\n carts[device_id].append(item)\n return {\"cart_size\": len(carts[device_id])}\n\n@app.get(\"/cart\")\nasync def get_cart(device_id: DeviceId):\n return {\"items\": carts.get(device_id, [])}\n```\n\n### Feature Flag Management\n\n```python\nimport hashlib\n\n@app.get(\"/feature/{feature_name}\")\nasync def get_feature_flag(feature_name: str, device_id: DeviceId):\n # Consistent feature assignment based on device ID\n hash_input = f\"{feature_name}:{device_id}\"\n hash_value = int(hashlib.md5(hash_input.encode()).hexdigest()[:8], 16)\n \n enabled = hash_value % 100 < 50 # 50% rollout\n return {\"feature\": feature_name, \"enabled\": enabled}\n```\n\n## Configuration Examples\n\n### Development Setup\n\n```python\n# Relaxed settings for local development\napp.add_middleware(\n DeviceMiddleware,\n cookie_secure=False, # Allow HTTP\n cookie_samesite=\"lax\", # Relaxed policy\n security_strategy=PlaintextStrategy(), # No encryption overhead\n)\n```\n\n### Production Setup\n\n```python\nimport os\nfrom fastapi_device_id import EncryptedStrategy\n\n# Strict security for production\napp.add_middleware(\n DeviceMiddleware,\n cookie_secure=True, # HTTPS only\n cookie_httponly=True, # No JavaScript access\n cookie_samesite=\"strict\", # Strict policy\n security_strategy=EncryptedStrategy(\n key=os.environ[\"DEVICE_ID_ENCRYPTION_KEY\"],\n algorithm=\"fernet\"\n ),\n)\n```\n\n### Short-lived Sessions with JWT\n\n```python\nfrom fastapi_device_id import JWTStrategy\n\n# JWT tokens that expire after 24 hours\napp.add_middleware(\n DeviceMiddleware,\n security_strategy=JWTStrategy(\n secret=\"your-jwt-secret\",\n expiration_hours=24\n ),\n)\n```\n\n### High-Security Setup\n\n```python\nimport os\nfrom fastapi_device_id import EncryptedStrategy\n\n# Maximum security configuration\napp.add_middleware(\n DeviceMiddleware,\n cookie_secure=True,\n cookie_httponly=True,\n cookie_samesite=\"strict\",\n cookie_max_age=7 * 24 * 60 * 60, # 1 week\n security_strategy=EncryptedStrategy(\n key=os.environ[\"DEVICE_ID_ENCRYPTION_KEY\"],\n algorithm=\"aes-256-gcm\", # Strong encryption\n iterations=200000, # Higher security\n ),\n)\n```\n\n## Requirements\n\n- Python 3.8+\n- FastAPI 0.68.0+\n- Starlette 0.14.0+\n\n### Optional Dependencies\n\nFor JWT strategy support:\n```bash\npip install \"fastapi-device-id[jwt]\"\n```\n\nFor encryption strategy support:\n```bash\npip install \"fastapi-device-id[crypto]\"\n```\n\nFor development:\n```bash\npip install \"fastapi-device-id[dev]\"\n```\n\nFor all features:\n```bash\npip install \"fastapi-device-id[jwt,crypto,dev]\"\n```\n\n## Production Checklist\n\nBefore deploying to production, ensure:\n\n- [ ] **Security Strategy**: Use `EncryptedStrategy` or `JWTStrategy` instead of `PlaintextStrategy`\n- [ ] **Environment Variables**: Store encryption keys in `os.environ`, never in code\n- [ ] **Cookie Security**: Set `cookie_secure=True` for HTTPS-only cookies\n- [ ] **SameSite Policy**: Use `cookie_samesite=\"strict\"` for maximum security\n- [ ] **Key Rotation**: Plan for periodic encryption key rotation\n- [ ] **Monitoring**: Log device ID operations for debugging\n- [ ] **Privacy Policy**: Update your privacy policy to mention device tracking\n- [ ] **GDPR Compliance**: Implement cookie consent if required in your jurisdiction\n\n### Example Production Configuration\n\n```python\nimport os\nfrom fastapi_device_id import DeviceMiddleware, EncryptedStrategy\n\napp.add_middleware(\n DeviceMiddleware,\n cookie_secure=True,\n cookie_httponly=True,\n cookie_samesite=\"strict\",\n security_strategy=EncryptedStrategy(\n key=os.environ[\"DEVICE_ID_ENCRYPTION_KEY\"],\n algorithm=\"fernet\"\n ),\n)\n```\n\n## Contributing\n\nWe welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.\n\n### Development Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/ideatives/fastapi-device-id.git\ncd fastapi-device-id\n\n# Install development dependencies\npip install -e \".[dev]\"\n\n# Run tests\npytest\n\n# Format code\nblack src tests\nruff --fix src tests\n\n# Type checking\nmypy src\n```\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Changelog\n\nSee [CHANGELOG.md](CHANGELOG.md) for version history.\n\n## Security\n\nFor security issues, please see our [Security Policy](SECURITY.md).",
"bugtrack_url": null,
"license": null,
"summary": "Drop-in device tracking for FastAPI - persistent IDs without user accounts",
"version": "0.1.0",
"project_urls": {
"Bug Tracker": "https://github.com/ideatives/fastapi-device-id/issues",
"Documentation": "https://github.com/ideatives/fastapi-device-id",
"Homepage": "https://github.com/ideatives/fastapi-device-id",
"Repository": "https://github.com/ideatives/fastapi-device-id"
},
"split_keywords": [
"a-b-testing",
" analytics",
" anonymous-tracking",
" cookie",
" device-tracking",
" fastapi",
" middleware",
" rate-limiting",
" session-management",
" starlette",
" uuid",
" web-analytics"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "b0824a07db6314203d4db56e41722b87c3718cb0e40004f4c49e3e0d9d29e0d8",
"md5": "b76e7c71094ff2e58160cfdbffc5b199",
"sha256": "0b0ab0a439e9bcfd5af94fa09e2a0117487fa06865a533f4e6e45e5466180b58"
},
"downloads": -1,
"filename": "fastapi_device_id-0.1.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "b76e7c71094ff2e58160cfdbffc5b199",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 13479,
"upload_time": "2025-09-13T17:13:38",
"upload_time_iso_8601": "2025-09-13T17:13:38.010420Z",
"url": "https://files.pythonhosted.org/packages/b0/82/4a07db6314203d4db56e41722b87c3718cb0e40004f4c49e3e0d9d29e0d8/fastapi_device_id-0.1.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "a3279618ad9ce64032beceb05c0e34bbc3a59092c629511b18e32a41097d8082",
"md5": "d97602b1f9454798b396d874929b87ff",
"sha256": "cbf294b1071fab2dec8d19630ec6b2dacf01ff63ad397583fb549da6ea5beed2"
},
"downloads": -1,
"filename": "fastapi_device_id-0.1.0.tar.gz",
"has_sig": false,
"md5_digest": "d97602b1f9454798b396d874929b87ff",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 28567,
"upload_time": "2025-09-13T17:13:39",
"upload_time_iso_8601": "2025-09-13T17:13:39.544209Z",
"url": "https://files.pythonhosted.org/packages/a3/27/9618ad9ce64032beceb05c0e34bbc3a59092c629511b18e32a41097d8082/fastapi_device_id-0.1.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-09-13 17:13:39",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "ideatives",
"github_project": "fastapi-device-id",
"github_not_found": true,
"lcname": "fastapi-device-id"
}