I’ve been attempting to upload a PDF to S3 using a Next.js route handler. However, I’m encountering a server error 500 when sending the post request. When I tried sending the request without the PDF file, it was successful. It seems that the code for uploading the PDF is the issue.
import { dbConnect } from "@/lib/db";
import { Program, User } from "@/models/userModel";
import { Upload } from "@aws-sdk/lib-storage";
import { NextRequest, NextResponse } from "next/server";
import { S3Client } from "@aws-sdk/client-s3";
const s3Client = new S3Client({
region: process.env.AWS_S3_REGION,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
},
});
async function uploadFileToS3(file: Buffer, fileName: string, userId: string) {
const params = {
Bucket: process.env.AWS_S3_BUCKET_NAME!,
Key: `pdfs/${userId}-${Date.now()}-${fileName}`,
Body: file,
ContentType: "application/pdf",
};
try {
const uploader = new Upload({
client: s3Client,
params: params,
});
const response = await uploader.done();
console.log("Successfully uploaded file to S3", response);
return response.Key;
} catch (error) {
console.error("Error uploading file to S3", error);
throw error;
}
}
// Add a user program
export const POST = async (request: NextRequest) => {
// Extract userId from query parameters
const url = new URL(request.url);
const userId = url.searchParams.get("userId");
const { name, from, to, pdf } = await request.json();
if (!name || !from || !to || !userId) {
return NextResponse.json({
message: "Missing required fields",
status: 400,
});
}
await dbConnect();
// Validate the user ID
const userExists = await User.findById(userId);
if (!userExists) {
return NextResponse.json({
message: "User not found",
status: 404,
});
}
// Update DB
try {
let pdfUrl = null;
if (pdf) {
const buffer = Buffer.from(pdf, "base64");
await uploadFileToS3(buffer, pdf.name, userId!);
pdfUrl = `https://${process.env.AWS_S3_BUCKET_NAME}.s3.amazonaws.com/pdfs/${userId}-${pdf.name}`;
}
// Form a DB payload
const newProgram = {
name,
from: new Date(from), // Ensure dates are properly formatted
to: new Date(to),
pdf: pdfUrl,
user: userExists._id,
};
const createdProgram = await Program.create(newProgram);
return NextResponse.json({
message: "Program has been created",
status: 201,
program: createdProgram,
});
} catch (error) {
console.error("Error creating program:", error);
return NextResponse.json({
error: error,
// error: "An error occurred while creating the program. Please try again.",
status: 500,
});
}
};
Upload images seems to work pretty well but pdf has some issues.
New contributor
isaac maina is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.