Search code examples
node.jsexpressamazon-s3herokugraphicsmagick

S3 images load locally, not on Heroku


Here is how I set up the AWS sdk for node, along with a test to see if there is an error

AWS.config.update({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: 'us-east-2'
})
const s3 = new AWS.S3()
s3.getObject({Bucket: process.env.S3_BUCKET_NAME, Key: '201706221542580.JPG'}, function(err, data) {
    console.log('ERROR?')
    console.log(err)
})

Variable err is null locally and on Heroku. Yet, images only load locally. Is this a CORS issue I need to resolve? I put the following CORS setup in the bucket hoping it would work, but to no avail.

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
   <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

Here is how I thumbnail the images server side:

app.get('/product_thumb/', (req, res, next) => {
    if (!req.query.patch) {
        return res.sendStatus(422)
    }
    res.contentType(req.query.patch);
    const stream = s3.getObject({Bucket: process.env.S3_BUCKET_NAME, Key: req.query.patch}).createReadStream()
    thumbnailImage(stream).pipe(res)
})

const thumbnailImage = (stream) => {
    let width = 100
    return gm(stream)
            .thumbnail(width)
            .stream()
}

and on the client with React:

<img src={'/product_thumb/?patch=' + props.src} onError={(e) => { e.target.onerror = null; e.target.src = "/img/missing.png" }}/>

I also tried setting all my environmental variables to simulate a production environment and even ran heroku local, but it always works on my machine. I also verified that my configuration environmental variables for S3 (retrieved with process.env.AWS_VARAIABLE for example) are exactly the same locally and on Heroku.


Solution

  • GraphicsMagick wasn't installed on the Heroku server. After adding the following buildpack, it worked perfectly. https://github.com/xerpa/heroku-buildpack-graphicsmagick.git