Optimize Google Antigravity applications with Cloudflare including edge caching, Workers, R2 storage, and security features.
# Cloudflare Edge Optimization
Optimize your Google Antigravity applications with Cloudflare edge services. This guide covers caching strategies, Workers, R2 storage, and security configurations.
## Cloudflare Configuration
Set up optimal Cloudflare settings:
```typescript
// cloudflare/page-rules.ts
// Configure via Cloudflare Dashboard or API
const pageRules = [
{
target: "*antigravityai.directory/_next/static/*",
actions: {
cacheLevel: "cacheEverything",
edgeCacheTTL: 31536000, // 1 year
browserCacheTTL: 31536000,
},
},
{
target: "*antigravityai.directory/api/*",
actions: {
cacheLevel: "bypass",
securityLevel: "high",
},
},
{
target: "*antigravityai.directory/*",
actions: {
cacheLevel: "standard",
edgeCacheTTL: 7200, // 2 hours
browserCacheTTL: 3600, // 1 hour
minify: {
javascript: true,
css: true,
html: true,
},
},
},
];
```
## Cloudflare Worker for Edge Logic
Implement edge logic with Workers:
```typescript
// workers/edge-handler.ts
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
// A/B testing at the edge
if (url.pathname === "/" || url.pathname === "/prompts") {
const cookie = request.headers.get("cookie") || "";
const variant = cookie.includes("ab_variant=")
? cookie.match(/ab_variant=(\w+)/)?.[1]
: Math.random() > 0.5 ? "a" : "b";
const response = await fetch(request);
const newResponse = new Response(response.body, response);
if (!cookie.includes("ab_variant=")) {
newResponse.headers.set(
"Set-Cookie",
`ab_variant=${variant}; Path=/; Max-Age=604800`
);
}
newResponse.headers.set("X-AB-Variant", variant);
return newResponse;
}
// Geolocation-based routing
const country = request.cf?.country || "US";
if (url.pathname.startsWith("/api/") && ["CN", "RU"].includes(country)) {
return new Response("Access denied", { status: 403 });
}
// Rate limiting
const clientIP = request.headers.get("CF-Connecting-IP") || "";
const rateLimitKey = `rate:${clientIP}`;
const requests = await env.KV.get(rateLimitKey);
const count = parseInt(requests || "0", 10);
if (count > 100) {
return new Response("Rate limit exceeded", { status: 429 });
}
await env.KV.put(rateLimitKey, String(count + 1), { expirationTtl: 60 });
return fetch(request);
},
};
```
## R2 Storage Integration
Use R2 for edge-optimized storage:
```typescript
// lib/cloudflare/r2-client.ts
import { S3Client, PutObjectCommand, GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
// R2 is S3-compatible
const r2Client = new S3Client({
region: "auto",
endpoint: `https://${process.env.CF_ACCOUNT_ID}.r2.cloudflarestorage.com`,
credentials: {
accessKeyId: process.env.R2_ACCESS_KEY_ID!,
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
},
});
export async function uploadToR2(
key: string,
body: Buffer | ReadableStream,
contentType: string
): Promise<string> {
await r2Client.send(
new PutObjectCommand({
Bucket: process.env.R2_BUCKET_NAME!,
Key: key,
Body: body,
ContentType: contentType,
})
);
// Return public URL via Cloudflare CDN
return `https://cdn.antigravityai.directory/${key}`;
}
export async function getSignedR2Url(key: string): Promise<string> {
const command = new GetObjectCommand({
Bucket: process.env.R2_BUCKET_NAME!,
Key: key,
});
return getSignedUrl(r2Client, command, { expiresIn: 3600 });
}
```
## Cache Headers in Next.js
Optimize caching from your application:
```typescript
// next.config.ts
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
async headers() {
return [
{
source: "/_next/static/:path*",
headers: [
{
key: "Cache-Control",
value: "public, max-age=31536000, immutable",
},
{
key: "CDN-Cache-Control",
value: "public, max-age=31536000, immutable",
},
],
},
{
source: "/api/:path*",
headers: [
{
key: "Cache-Control",
value: "no-store, must-revalidate",
},
{
key: "CDN-Cache-Control",
value: "no-store",
},
],
},
{
source: "/:path*",
headers: [
{
key: "Cache-Control",
value: "public, max-age=0, s-maxage=86400, stale-while-revalidate=86400",
},
],
},
];
},
};
export default nextConfig;
```
## Security Configuration
Harden security at the edge:
```typescript
// Cloudflare security settings
const securitySettings = {
// WAF Rules
waf: {
enabled: true,
mode: "block",
rules: [
"OWASP Core Ruleset",
"Cloudflare Managed Ruleset",
],
},
// Bot Management
botManagement: {
enabled: true,
blockAI: false,
challengeBots: true,
},
// DDoS Protection
ddos: {
sensitivityLevel: "medium",
rulesets: ["HTTP DDoS Attack Protection"],
},
};
```
## Best Practices
1. **Cache Static Assets**: Set long TTLs for immutable static files
2. **Edge Caching**: Use CDN-Cache-Control for fine-grained control
3. **R2 for Assets**: Use R2 for user uploads with CDN delivery
4. **Workers for Logic**: Implement edge logic without origin roundtrips
5. **Security Headers**: Configure WAF and bot protection
6. **Analytics**: Monitor cache hit ratios and performanceThis cloudflare prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their cloudflare implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For cloudflare projects, consider mentioning your framework version, coding style, and any specific libraries you're using.