Users of my app, Beluga, upload property photos and videos, and I needed every one of those files to carry a watermark but I didn't want to do it by hand, and I didn't want to push the work into the Flutter app or onto my backend server.

My uploads already went straight from the Flutter app to Amazon S3 through presigned URLs. So, I kept that and added one small piece: when a file lands in S3, a Lambda function watermarks it and writes it back to the same object key. The app and the backend don't change, and every stored URL keeps working.

This post walks through the whole build: the AWS setup, the handler, packaging Sharp and FFmpeg with Docker (from Windows), the presigned upload, and testing.

What you'll build

  • An S3 bucket for uploads, with public read for the uploads/ folder only
  • A Lambda function (Node.js 24.x) that runs whenever a file is uploaded to uploads/
  • Sharp to watermark .jpg, .jpeg, .png, and .webp images
  • FFmpeg in a Lambda layer to watermark .mp4 videos
  • A "replace in place" step that overwrites the original without starting an infinite loop

Figure 1: Architecture of the watermarking pipeline, from Flutter upload to the watermarked object replacing the original in S3

The flow:

  1. The Flutter app asks the backend for a presigned URL and uploads the file directly to S3.
  2. S3 sends an ObjectCreated event to Lambda.
  3. Lambda downloads the file and the watermark PNG. Images go to Sharp, MP4s go to FFmpeg.
  4. Lambda uploads the result to a temporary key, copies it over the original key, and deletes the temporary file.

Why S3 events and Lambda

  • Uploads stay direct. The app still sends files straight to S3.
  • Processing is asynchronous. Nobody waits for a video to re-encode before their upload finishes.
  • Every file is covered. The watermark doesn't depend on each client doing the right thing.
  • The backend stays focused on handling API requests.

Prerequisites

  • An AWS account with access to S3, Lambda, and IAM
  • Docker Desktop (I used Windows; any Docker install works)
  • PowerShell. On macOS or Linux, replace the backtick line breaks with \ and $($PWD.Path) with $(pwd).
  • A transparent PNG to use as your watermark

You don't need Node.js installed locally. Every npm and node command runs inside AWS's official Lambda container image.

Names used in this guide

Replace these with your own names, and keep them consistent, because later steps refer back to them.

Resource Name in this guide
S3 bucket aws-watermark-demo
Upload folder (prefix) uploads/
Watermark object key watermark-assets/LeksyMark.png
Temporary prefix watermark-tmp/
IAM role LeksykingWatermarkLambdaRole
Inline S3 policy LeksykingWatermarkS3Access
Lambda function aws-media-watermark
Lambda layer aws-ffmpeg-layer
Region eu-north-1 (the bucket and the function must be in the same region)

The full source is on GitHub: aws-media-watermark. This post shows the important parts and explains them.

Step 1: Create the bucket

Bucket settings

In the S3 console, create a bucket with these settings:

  • Bucket type: General purpose
  • Bucket namespace: Global namespace
  • Object Ownership: ACLs disabled (recommended)
  • Block all public access: off. The bucket policy below needs it off. If your app only serves files through presigned GET URLs, leave it on and skip the bucket policy.
  • Bucket Versioning: enabled
  • Default encryption: default

Why ACLs disabled? With ACLs disabled, S3 rejects any request that sets an ACL. If your backend signs uploads with ACL: "public-read", the upload fails with AccessControlListNotSupported: The bucket does not allow ACLs. The fix is to remove the ACL from the presigned URL (Step 11) and make files public with a bucket policy. One policy covers every file, including the watermarked copies the Lambda writes.

Make the upload folder publicly readable

Go to Permissions → Bucket policy → Edit and paste:

{ "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadUploads", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::aws-watermark-demo/uploads/*" } ] } 

Only uploads/ is public. The watermark PNG and the temporary files stay private. The policy grants s3:GetObject and not s3:GetObjectVersion, so the un-watermarked older versions that versioning keeps aren't publicly readable.

Upload the watermark PNG

  1. Open the bucket and go to the Objects tab.
  2. Click Create folder, name it watermark-assets, and click Create folder.
  3. Open watermark-assets, click Upload → Add files, choose your transparent PNG, and upload it.

Write down the full key (mine is watermark-assets/LeksyMark.png). You'll need it in Step 3.

Step 2: Create the Lambda execution role

The function needs to read media and the watermark, write processed files, delete its temporary files, and write logs.

Create the role

  1. In the IAM console, go to Roles → Create role.
  2. Set Trusted entity type to AWS service and Use case to Lambda. Click Next.
  3. Select the AWS-managed policy AWSLambdaBasicExecutionRole so the function can write CloudWatch logs. Click Next.
  4. Name the role LeksykingWatermarkLambdaRole, add a description such as "Execution role for S3 image and video watermark processing", and click Create role.

Add a scoped S3 policy

  1. Open the role and go to Permissions → Add permissions → Create inline policy. Switch to the JSON tab.
  2. Paste this, replacing aws-watermark-demo with your bucket name:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "ReadMediaAndWatermarkAssets", "Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::aws-watermark-demo/*"] }, { "Sid": "WriteProcessedMediaAndTemporaryFiles", "Effect": "Allow", "Action": ["s3:PutObject"], "Resource": ["arn:aws:s3:::aws-watermark-demo/*"] }, { "Sid": "DeleteTemporaryProcessingFiles", "Effect": "Allow", "Action": ["s3:DeleteObject"], "Resource": ["arn:aws:s3:::aws-watermark-demo/watermark-tmp/*"] } ] } 
  1. Click Next, name it LeksykingWatermarkS3Access, and click Create policy.
Permission Why it's needed
s3:GetObject Read the original media and the watermark. Also covers HeadObject and reading the source of a CopyObject.
s3:PutObject Write the temporary output, and write the final object with CopyObject.
s3:DeleteObject Clean up temporary files, only under watermark-tmp/.

The role should now list two policies: AWSLambdaBasicExecutionRole and LeksykingWatermarkS3Access.

Figure 2: The IAM role with both permission policies attached

Step 3: Create the Lambda function (no trigger yet)

Create and configure the function now, and connect the S3 trigger only after testing. That way the function can't touch real uploads before you've tested it.

  1. Open the Lambda console and confirm the region matches your bucket.
  2. Click Create Event Function → Author from scratch:
Setting Value
Function name aws-media-watermark
Runtime Node.js 26.x
ARM64 architecture x86_64 (leave the ARM64 toggle off)
Custom execution role Toggle Custom execution role on → Choose an existing role → LeksykingWatermarkLambdaRole
  1. Click Create Event Function.

Architecture matters. Sharp's native binaries and the FFmpeg binary we build later both target Linux x86_64. They won't run on an ARM64 function.

Memory and timeout

Under Configuration → General configuration, I set memory to 1024 MB and the timeout to 20 seconds. The default (128 MB) is too small even for images. Lambda gives CPU in proportion to memory, so more memory also makes processing faster.

For video, the input and output both sit in /tmp, which is 512 MB by default. If you accept long or high-resolution videos, raise the timeout and the ephemeral storage in the same panel, then confirm the values with a real test (Step 12).

Environment variables

Under Configuration → Environment variables → Edit, add:

Key Value
BUCKET_NAME aws-watermark-demo
WATERMARK_KEY watermark-assets/LeksyMark.png
TEMP_PREFIX watermark-tmp/

WATERMARK_KEY must match the key of your PNG exactly. Click Save.

Step 4: Install the function's dependencies with Docker

The function uses two npm packages:

  • sharp: fast image processing; it composites the PNG onto images.
  • @aws-sdk/client-s3: downloads, uploads, copies, and deletes S3 objects.

Why Docker? Sharp ships prebuilt native binaries for each OS and CPU. Run npm install on Windows and you get Windows binaries, which fail to load on Lambda's Linux. Running the install inside the official Lambda image gives you exactly the binaries Lambda needs.

Create the project folders

mkdir aws-media-watermark cd aws-media-watermark mkdir app mkdir ffmpeg-layer\bin 

The final layout:

aws-media-watermark/ ├── app/ ← becomes the function ZIP │ ├── package.json │ ├── index.mjs │ └── node_modules/ └── ffmpeg-layer/ ← becomes the layer ZIP ├── package.json ├── node_modules/ └── bin/ └── ffmpeg 

Create app/package.json

{ "name": "aws-media-watermark", "version": "1.0.0", "type": "module", "dependencies": { "@aws-sdk/client-s3": "^3.800.0", "sharp": "^0.34.0" } } 

"type": "module" lets the handler use import syntax.

Tip: I created every file from PowerShell with a here-string, so I never had to leave the terminal:

@' { ...file content... } '@ | Set-Content -Encoding utf8 .\app\package.json 

Install inside the Lambda container

From the aws-media-watermark folder:

docker run --rm --platform linux/amd64 ` --entrypoint /bin/sh ` --mount "type=bind,source=$($PWD.Path)\app,target=/var/task" ` -w /var/task ` public.ecr.aws/lambda/nodejs:26 ` -c "npm install --omit=dev" 
  • --platform linux/amd64 builds for x86_64, even on Apple Silicon or other ARM machines.
  • --mount ... maps your app folder to /var/task, so node_modules ends up on your disk.
  • --entrypoint /bin/sh is required. The image's default entrypoint starts the Lambda runtime instead of running your command.
  • npm install --omit=dev installs only production dependencies.

Step 5: Build the FFmpeg layer

FFmpeg isn't included in the Lambda Node.js runtime, so you have to bring your own binary. I packaged it as a Lambda layer: a ZIP that Lambda extracts into /opt next to your function. That keeps the large binary out of the function ZIP, so code updates stay small.

The easiest Linux x64 static build I found was the ffmpeg-static npm package, which downloads a prebuilt binary during install.

Create ffmpeg-layer/package.json

{ "name": "aws-ffmpeg-layer", "version": "1.0.0", "private": true, "dependencies": { "ffmpeg-static": "^5.2.0" } } 

Install it and copy the binary into bin/

docker run --rm --platform linux/amd64 ` --entrypoint /bin/sh ` --mount "type=bind,source=$($PWD.Path)\ffmpeg-layer,target=/var/task" ` -w /var/task ` public.ecr.aws/lambda/nodejs:26 ` -c "npm install --omit=dev && cp node_modules/ffmpeg-static/ffmpeg bin/ffmpeg && chmod 755 bin/ffmpeg" 

The layer only needs bin/ffmpeg. Lambda extracts layers into /opt, so the binary ends up at /opt/bin/ffmpeg, which is the path the handler uses. chmod 755 makes it executable.

Check the binary

Confirm that it runs on Lambda's OS and has the two features the handler needs, the libx264 encoder and the overlay filter:

docker run --rm --platform linux/amd64 ` --mount "type=bind,source=$($PWD.Path)\ffmpeg-layer,target=/var/task" ` --entrypoint /bin/sh ` public.ecr.aws/lambda/nodejs:26 ` -c '/var/task/bin/ffmpeg -version | head -1; /var/task/bin/ffmpeg -hide_banner -encoders 2>/dev/null | grep libx264; /var/task/bin/ffmpeg -hide_banner -filters 2>/dev/null | grep overlay' 

My build reported ffmpeg version 7.0.2-static, with libx264 and overlay both listed.

Figure 3: Verifying the FFmpeg binary inside the Lambda container: the version, the libx264 encoder, and the overlay filter

Step 6: Write the handler

Create app/index.mjs. The complete file is in the repo. Here are the parts that do the real work, in the order a file goes through them.

Configuration

const s3 = new S3Client({}); const BUCKET = process.env.BUCKET_NAME; const WATERMARK_KEY = process.env.WATERMARK_KEY || "watermark-assets/LeksyMark.png"; const TEMP_PREFIX = process.env.TEMP_PREFIX || "watermark-tmp/"; const FFMPEG = "/opt/bin/ffmpeg"; // provided by the layer const HANDLED_EVENTS = new Set([ "ObjectCreated:Put", "ObjectCreated:Post", "ObjectCreated:CompleteMultipartUpload", ]); 

HANDLED_EVENTS covers every way a file can be uploaded: a single PUT, a browser-style POST, and a multipart upload, which is common for large videos. ObjectCreated:Copy is deliberately missing. The function's own final write is a copy, so ignoring copies is what breaks the loop.

Deciding what to process

async function processRecord(record) { if (!HANDLED_EVENTS.has(record.eventName)) return; // S3 URL-encodes keys in events, and spaces arrive as "+". const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, " ")); if (key.startsWith(TEMP_PREFIX) || key === WATERMARK_KEY) return; const head = await s3.send( new HeadObjectCommand({ Bucket: BUCKET, Key: key }) ); if (head.Metadata?.watermarked === "true") return; const media = resolveMedia(key, head.ContentType); if (!media) return; // not an image or video we handle // ...download, process, and replace (below) } 

(The real code logs a reason for each skip, so you can see in CloudWatch why a file was ignored.)

  • Key decoding. my photo.jpg arrives as my+photo.jpg. Without decoding, the download fails.
  • Temp prefix and watermark skipped. This is a safety net in case the trigger is ever widened beyond uploads/.
  • watermarked=true skipped. S3 delivers events at least once, so the same upload can occasionally arrive twice.
  • resolveMedia identifies the file from its extension. If the key has no extension (a bare UUID, say), it falls back to the Content-Type:
export function resolveMedia(key, contentType) { const ext = path.extname(key).toLowerCase(); if (MEDIA_BY_EXT[ext]) return { ext, ...MEDIA_BY_EXT[ext] }; const type = (contentType || "").split(";")[0].trim().toLowerCase(); const fallbackExt = EXT_BY_CONTENT_TYPE[type]; if (fallbackExt) return { ext: fallbackExt, ...MEDIA_BY_EXT[fallbackExt] }; return null; } 

Watermarking images with Sharp

export async function watermarkImage(input, output, logo, ext) { // Apply EXIF orientation so phone photos aren't sideways. const orientedBuffer = await sharp(input).rotate().toBuffer(); const { width, height } = await sharp(orientedBuffer).metadata(); const watermark = await sharp(logo) .resize({ width: Math.max(1, Math.round(width * 0.25)), height: Math.max(1, Math.round(height * 0.25)), fit: "inside", withoutEnlargement: true, }) .png() .toBuffer(); const wm = await sharp(watermark).metadata(); const margin = Math.max(8, Math.round(Math.min(width, height) * 0.025)); const left = Math.max(0, width - wm.width - margin); const top = Math.max(0, height - wm.height - margin); let outputImage = sharp(orientedBuffer).composite([ { input: watermark, left, top, blend: "over" }, ]); if (ext === ".jpg" || ext === ".jpeg") outputImage = outputImage.jpeg({ quality: 88 }); else if (ext === ".webp") outputImage = outputImage.webp({ quality: 88 }); else outputImage = outputImage.png(); await outputImage.toFile(output); } 
  • Orientation. Phones often store portrait photos as landscape pixels plus an EXIF "rotate 90°" tag. Sharp drops that tag on output, so without .rotate() a portrait photo comes out sideways.
  • Size. The logo fits inside 25% of the image's width and height, so it looks the same on a thumbnail and on a 4K photo. It also never ends up larger than a very wide panorama (Sharp throws an error if the overlay is bigger than the image). withoutEnlargement stops a small logo from being blown up and blurred.
  • Position. Bottom-right, with a margin of 2.5% of the shorter side (at least 8 px).
  • Blending. blend: "over" keeps the PNG's transparency.
  • Quality. JPEG and WebP are re-encoded at quality 88, a good balance of size and quality. PNG stays lossless.
  • A privacy bonus. By default, Sharp doesn't copy EXIF metadata into the output, so GPS coordinates from users' phones are removed from the watermarked file.

Watermarking video with FFmpeg

Sharp handles still images only. For video, every frame has to be decoded, overlaid, and re-encoded, which is FFmpeg's job. The handler runs it as a child process:

async function watermarkVideo(input, output, logo) { await runFFmpeg([ "-hide_banner", "-loglevel", "error", "-y", "-i", input, // input 0: the video "-i", logo, // input 1: the PNG "-filter_complex", "[1:v]scale=250:-2[wm];[0:v][wm]overlay=W-w-24:H-h-24:format=auto,format=yuv420p[v]", "-map", "[v]", "-map", "0:a?", "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-c:a", "copy", "-movflags", "+faststart", "-max_muxing_queue_size", "2048", output, ]); } 
  • scale=250:-2 resizes the logo to 250 px wide. -2 keeps the aspect ratio and rounds the height to an even number, which H.264 needs.
  • overlay=W-w-24:H-h-24 places it 24 px from the bottom-right corner (W/H are the video's size, w/h the logo's).
  • -map 0:a? keeps the audio if there is any. The ? stops silent videos from failing.
  • -c:a copy passes the audio through untouched, so only the video is re-encoded.
  • libx264 -preset veryfast -crf 23 is H.264 at the encoder's default quality, tuned for speed, which matters when you pay per millisecond.
  • +faststart moves the MP4 index to the front so playback starts before the whole file downloads.

runFFmpeg wraps spawn. It resolves when FFmpeg exits with code 0. Otherwise it rejects with the last 20 KB of FFmpeg's stderr, so failures appear in CloudWatch with a real error message.

Replacing the original safely

The handler doesn't upload directly over the original. It goes through a temporary object:

// 1. Upload the result to watermark-tmp/<uuid>.<ext> await s3.send(new PutObjectCommand({ Bucket: BUCKET, Key: tempKey, Body: createReadStream(outputPath), ContentLength: outputStat.size, ContentType: media.contentType, Metadata: { watermarked: "true", originalkey: key }, })); // 2. Server-side copy over the ORIGINAL key await s3.send(new CopyObjectCommand({ Bucket: BUCKET, Key: key, CopySource: encodeCopySource(BUCKET, tempKey), MetadataDirective: "REPLACE", Metadata: { ...(head.Metadata || {}), watermarked: "true" }, ContentType: media.contentType, // plus CacheControl, ContentLanguage, Expires, and an inline // ContentDisposition, copied from the original when present })Source:https://dev.to/leksyking/watermark-every-upload-automatically-with-s3-lambda-sharp-and-ffmpeg-118e

Related posts