S3 File Upload

Anyone got an idea what I am missing here:
And this is my api route:
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { randomUUID } from 'crypto';
import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    try {
        const accountid = process.env.CLOUDFLARE_ACCOUNT_ID

        const s3 = new S3Client({
            endpoint: `https://${accountid}.r2.cloudflarestorage.com`,
            region: process.env.R2_REGION,
            credentials: {
                accessKeyId: process.env.WRITE_CLOUDFLARE_R2_ACCESS_KEY_ID!,
                secretAccessKey: process.env.WRITE_CLOUDFLARE_R2_SECRET_ACCESS_KEY!,
            }
        })

        // Check if the file is present in the request body
        if (!req.body || !req.body.file) {
            throw new Error('No file data found in the request');
        }

        console.log("api file upload", req.body.file)

        // Get the file content and filename from the request
        const file = req.body.file; // Assuming the uploaded file is in a 'file' field in the form-data
        const fileContent = file.buffer;
        const filename = file.name;

        const uniqueName = `${randomUUID()}-${filename}`
        const conditions = [['content-length-range', 0, 10485760]]


        // Prepare the parameters for the S3 PutObjectCommand
        const params = {
            Bucket: 'test',
            Key: uniqueName,
            Body: fileContent,
        };
        const command = new PutObjectCommand(params);
        await s3.send(command);
        res.status(200).json({ message: 'File uploaded successfully' });
    } catch (error) {
        console.error('Error uploading file to S3:', error);
        res.status(500).json({ message: 'Error uploading file to S3' });
    }
}


But my req.body keeps returning undefined, any ideas?

I am using the v3 package:

aws-sdk/client-s3
Was this page helpful?