1

I'm trying to get an s3.getObject() running inside an async getInitialProps() function in a nextJS project, but I can't for the love of it figure out how to get the results prepped to they can be returned as an object (which is needed for getInitialProps() and nextJS' SSR to work properly).

Here is the code:

static async getInitialProps({ query }) {
  const AWS = require('aws-sdk');
  const s3 = new AWS.S3({
    credentials: {
      accessKeyId: KEY
      secretAccessKey: KEY
    }
  });

  // The id from the route (e.g. /img/abc123987)
  let filename = query.id;

  const params = {
    Bucket: BUCKETNAME
    Key: KEYDEFAULTS + '/' + filename
  };

  const res = await s3.getObject(params, (err, data) => {
    if (err) throw err;
    let imgData = 'data:image/jpeg;base64,' + data.Body.toString('base64');
    return imgData;
  });

  return ...
}

The idea is to fetch an image from S3 and return it as base64 code (just to clear things up).

1 Answer 1

2

From your code, s3.getObject, works with callback. you need to wait for the callback to be called.

You can achieve it by converting this callback into a promise.


static async getInitialProps({ query }) {
  const AWS = require('aws-sdk');
  const s3 = new AWS.S3({
    credentials: {
      accessKeyId: KEY
      secretAccessKey: KEY
    }
  });

  // The id from the route (e.g. /img/abc123987)
  let filename = query.id;

  const params = {
    Bucket: BUCKETNAME
    Key: KEYDEFAULTS + '/' + filename
  };

  const res = await new Promise((resolve, reject) => {
    s3.getObject(params, (err, data) => {
      if (err) reject(err);
      let imgData = 'data:image/jpeg;base64,' + data.Body.toString('base64');
      resolve(imgData);
    });
  });


  return ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.