Watermark Every Upload Automatically with S3, Lambda, Sharp, and FFmpeg
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.webpimages - FFmpeg in a Lambda layer to watermark
.mp4videos - A "replace in place" step that overwrites the original without starting an infinite loop
The flow: The Flutter app asks the backend for a presigned URL and uploads the file directly to S3. S3 sends an ObjectCreated event to Lambda. Lambda downloads the file and the watermark PNG. Images go to Sharp, MP4s go to FFmpeg. Lambda uploads the result to a temporary key, copies it over the original key, and deletes the temporary file.
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.
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
Open the bucket and go to the Objects tab. Click Create folder, name it watermark-assets, and click Create folder. 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
In the IAM console, go to Roles → Create role. Set Trusted entity type to AWS service and Use case to Lambda. Click Next. Select the AWS-managed policy AWSLambdaBasicExecutionRole so the function can write CloudWatch logs. Click Next.
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
Open the role and go to Permissions → Add permissions → Create inline policy. Switch to the JSON tab. 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/*"]
}
]
}
Click Next, name it LeksykingWatermarkS3Access, and click Create policy.
- Permission Why it's needed
s3:GetObjectRead the original media and the watermark. Also covers HeadObject and reading the source of a CopyObject. s3:PutObjectWrite the temporary output, and write the final object with CopyObject.s3:DeleteObjectClean up temporary files, only underwatermark-tmp/.
The role should now list two policies: AWSLambdaBasicExecutionRole and LeksykingWatermarkS3Access.
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.
Open the Lambda console and confirm the region matches your bucket. 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
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_NAMEaws-watermark-demo WATERMARK_KEYwatermark-assets/LeksyMark.pngTEMP_PREFIXwatermark-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/amd64builds for x86_64, even on Apple Silicon or other ARM machines.--mount ...maps your app folder to/var/task, sonode_modulesends up on your disk.--entrypoint /bin/shis required. The image's default entrypoint starts the Lambda runtime instead of running your command.npm install --omit=devinstalls 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.
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;
// ...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 orientat
Comments
No comments yet. Start the discussion.