Skip to content
GitHub Discord

Sharp in Lambda

Uses the Sharp library to resize images. In this example, it resizes a logo.png local file to 100x100 pixels.

sst.config.ts
{
nodejs: { install: ["sharp"] }
}

We don’t need a layer to deploy this because sharp comes with a pre-built binary for Lambda. This is handled by nodejs.install.

In dev, this uses the sharp npm package locally.

package.json
{
"dependencies": {
"sharp": "^0.33.5"
}
}

On deploy, SST will use the right binary from the sharp package for the target Lambda architecture.

sst.config.ts
const func = new sst.aws.Function("MyFunction", {
url: true,
handler: "index.handler",
nodejs: { install: ["sharp"] },
copyFiles: [{ from: "logo.png" }],
});
index.ts
import sharp from "sharp";
import { promises as fs } from "fs";
export async function handler() {
const imagePath = "logo.png";
try {
// Read the image file
const imageBuffer = await fs.readFile(imagePath);
// Resize the image
const resizedImage = await sharp(imageBuffer)
.resize(100, 100) // Resize to 100x100
.toBuffer();
// Convert the buffer to base64
const body = resizedImage.toString("base64");
console.log("Successfully resized logo.png");
return {
body,
statusCode: 200,
headers: {
"Content-Type": "image/png",
"Content-Disposition": "inline"
},
isBase64Encoded: true
};
} catch (error) {
console.log(error);
return {
statusCode: 500,
body: JSON.stringify("Error resizing image: " + error.message),
};
}
}

View the full example.