I am using this cloudinary function in my nextjs project
import { v2 as cloudinary, UploadApiResponse } from 'cloudinary'
import dotenv from 'dotenv'
dotenv.config()
const cloudinaryConfig = {
cloud_name: process.env.CloudName as string,
api_key: process.env.CloudapiKey as string,
api_secret: process.env.CloudapiSecret as string,
}
cloudinary.config(cloudinaryConfig)
export default async function uploadPDFtoCloud(
pdfFile: string,
): Promise<string> {
try {
const result: UploadApiResponse = await cloudinary.uploader.upload(
pdfFile,
{
folder: 'file_doc_pdf',
resource_type: 'raw',
type: 'authenticated',
},
)
return result.secure_url as string
} catch (error) {
console.error('Error Uploading file:', error)
throw new Error('Failed to upload PDF: ')
}
}
The problem is that this function is working in development normally and returning secure url but while running npm run build to test in production I encountered
Error Uploading file: {
message: `Server return invalid JSON response. Status Code 500. SyntaxError: Unexpected token
'<', "<!DOCTYPE "... is not valid JSON`,
name: 'Error',
http_code: 500
While build is still running and each time I test the function when I run the app, I get the same error ,I checked the env variables as all are coming right but after some testing the error is triggering at this code line
const result: UploadApiResponse = await cloudinary.uploader.upload(
pdfFile,
{
folder: 'file_doc_pdf',
resource_type: 'raw',
type: 'authenticated',
},
)
So what might be the problem that causing this error in production and why not in development!?
You should (in your case), upload the file as binary:
You have the error
500because the server can't handle your pdf. The problem is not cloudinary, the problem is actually how you get pdf file. Other part of your code seems to be ok.P.S. In any case,
console.log()you error to see the details P.S 2 : error in production very often relies to .env variables or CORS policy.