There seem to be questions for 3 years in the similar direction. I have the following code that should upload to cloudflare stream via TUS but I get CORS Error some answers mention to use your own server URL in TUS which makes no sense at all in the current setup so I am missing some viat information here. Could someone please help me:
The Backend API:
router.post('/generate-upload-url', async (req, res, next) => {
try {
const CLOUDFLARE_ACCOUNT_ID = process.env.CLOUDFLARE_ACCOUNT_ID; // Taken from environment variables
const CLOUDFLARE_API_TOKEN = process.env.CLOUDFLARE_API_TOKEN; // Taken from environment variables
const endpoint = `https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/stream?direct_user=true`;
const fileSize = req.body.size; // Extracting the size from the request body
// const uploadLength = Array.isArray(req.headers['upload-length'])
// ? req.headers['upload-length'][0]
// : req.headers['upload-length'];
const uploadMetadata = Array.isArray(req.headers['upload-metadata'])
? req.headers['upload-metadata'][0]
: req.headers['upload-metadata'];
const cloudflareResponse = await fetch(endpoint, {
method: 'POST',
headers: {
Authorization: `Bearer ${CLOUDFLARE_API_TOKEN}`,
'Tus-Resumable': '1.0.0',
'Upload-Length': fileSize, // Assuming these headers are provided by the client
'Upload-Metadata': uploadMetadata,
},
});
if (cloudflareResponse.ok) {
const destination = cloudflareResponse.headers.get('Location');
res.json({
message: 'Generated Cloudflare one-time upload URL successfully.',
uploadURL: destination,
});
} else {
const errorData = await cloudflareResponse.json();
res.status(400).json({
error: 'Failed to generate Cloudflare upload URL',
details: errorData,
});
}
} catch (err) {
next(err);
}
});
The call in the client
const uploadToCloudFlare = async (file) => {
const fileSize = file.size; // Getting the size of the file in bytes
const { uploadURL } = await generateUploadURL(fileSize);
console.log(uploadURL);
if (!uploadURL) {
console.error('Could not generate one-time URL');
return;
}
const upload = new Upload(file, {
endpoint: uploadURL,
retryDelays: [0, 1000, 3000, 5000],
chunkSize: 50 * 1024 * 1024,
metadata: {
filename: file.name,
filetype: file.type,
},
onError: function (error) {
console.error('CloudFlare Upload Error:', error);
},
onProgress: function (bytesUploaded, bytesTotal) {
const percentage = ((bytesUploaded / bytesTotal) * 100).toFixed(2);
console.log(percentage);
setUploadProgress(parseFloat(percentage));
console.log(bytesUploaded, bytesTotal, percentage + '%');
},
onSuccess: function () {
console.log('Upload finished:', upload.url);
},
});
upload.start();
};