Untitled

 avatar
unknown
plain_text
4 months ago
1.4 kB
4
Indexable
// app/api/r2-upload/route.ts
import { NextResponse } from "next/server";
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";

// Create S3 client for Cloudflare R2
const s3Client = new S3Client({
  region: "auto",
  endpoint: process.env.R2_ENDPOINT,
  credentials: {
    accessKeyId: process.env.R2_ACCESS_KEY_ID || "",
    secretAccessKey: process.env.R2_SECRET_ACCESS_KEY || "",
  },
});

export async function POST(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const key = searchParams.get("key");
    
    if (!key) {
      return NextResponse.json(
        { error: "Key parameter is required" },
        { status: 400 }
      );
    }
    
    const contentType = request.headers.get("content-type") || "application/json";
    const body = await request.json();
    
    // Upload to R2 bucket
    const command = new PutObjectCommand({
      Bucket: process.env.R2_BUCKET_NAME,
      Key: key,
      Body: JSON.stringify(body),
      ContentType: contentType,
      CacheControl: "no-cache, no-store, must-revalidate",
    });
    
    await s3Client.send(command);
    
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Error uploading to R2:", error);
    return NextResponse.json(
      { error: "Failed to upload to R2" },
      { status: 500 }
    );
  }
}
Editor is loading...
Leave a Comment