- Newest
- Most votes
- Most comments
The issue you're encountering is related to typescript's type checking. The response.body expects a WritableStream, but TypeScript cannot infer that fileStream.Body is a ReadableStream. The ReadableStream from @aws-sdk/client-s3 does not directly extend NodeJS.ReadableStream, which is why TypeScript is having trouble understanding its type.
You can try a workaround by creating a custom WritableStream using Node.js's stream.Writable class. Here's how you can do it:
// Import necessary modules
import { Readable } from "stream";
import { Writable } from "stream";
import { NextRequest, NextResponse } from "next/server";
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
// Your existing code ...
// Pipe the S3 object stream to the response
if (fileStream.Body !== null) {
if (fileStream.Body instanceof Readable) {
// Create a custom writable stream
const customWritableStream = new Writable({
write(chunk, encoding, callback) {
response.write(chunk, encoding); // Write data to the response
callback(); // Call the callback function to indicate that writing is complete
},
});
// Pipe the S3 object stream to the custom writable stream
fileStream.Body.pipe(customWritableStream);
// Return the response
return NextResponse.json({ success: true, key });
} else {
// Handle non-readable stream type
}
} else {
// Handle the case where the file stream body is null
}
we're creating a custom writable stream using Node.js's stream.Writable class, which allows us to explicitly define the write function. Then, we pipe the S3 object stream to this custom writable stream and write the data to the response. Finally, we call the callback function to indicate that writing is complete. This should resolve the TypeScript error you're encountering.
Let me know if this helps
Relevant content
- Accepted Answerasked 3 years ago
- Accepted Answerasked 3 years ago
- asked 21 days ago
- asked 6 years ago
- AWS OFFICIALUpdated 2 years ago
- AWS OFFICIALUpdated 2 years ago
- AWS OFFICIALUpdated 2 years ago
I think we’re on the right path, but now it says: Property 'write' does not exist on type 'NextResponse<unknown>'.