Search code examples
node.jsamazon-s3signed-url

How to pipe a s3 getSignedUrl


I'm trying to pipe a signed url of an image I got stored in a bucket in S3.

When using regular "getObject" method I can do it like this

  app.get("/images/:key", (req, res) => {

    const key = req.params.key;
    const downloadParams = {
    Key: key,
    Bucket: bucketName,
  };
    const readStream = s3.getObject(downloadParams).createReadStream();
    readStream.pipe(res);

  });

But when I try with getSignedUrlPromise, I can't use the createReadStream method because it says it's not a function.

 const readStreamSigned = await s3
   .getSignedUrlPromise("getObject", downloadParams).createdReadStream // throws createReadStream is not a function

readStreamSigned.pipe(res)

How can I achieve that with getSignedUrl or getSignedUrlPromise?


Solution

  • Found a solution! inspired by this answer https://stackoverflow.com/a/65976684/4179240 in a high level what we want to do is this:

    1. Get the key of the item to search.
    2. Pass it with the params to getSignedUrlPromises.
    3. Get the generated url from the promise.
    4. Pipe the result from the callback of the get().

    I ended up doing it like this

      app.get("/images/:key", async (req, res) => {
        const key = req.params.key;
    
        const downloadParams = {
          Key: key,
          Bucket: bucketName,
        };
    
        const url = await s3.getSignedUrlPromise("getObject", downloadParams);
    
        https.get(readStream, (stream) => {
          stream.pipe(res);
        });
      });
    

    If you find a better way let me know! 😃