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.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
ObjectCreatedevent 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.
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 withAccessControlListNotSupported: 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
AWSLambdaBasicExecutionRoleso 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-demowith 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: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.
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_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/amd64builds for x86_64, even on Apple Silicon or other ARM machines. -
--mount ...maps yourappfolder 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; // 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.jpgarrives asmy+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=trueskipped. S3 delivers events at least once, so the same upload can occasionally arrive twice. -
resolveMediaidentifies the file from its extension. If the key has no extension (a bare UUID, say), it falls back to theContent-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).
withoutEnlargementstops 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:-2resizes the logo to 250 px wide.-2keeps the aspect ratio and rounds the height to an even number, which H.264 needs. -
overlay=W-w-24:H-h-24places it 24 px from the bottom-right corner (W/Hare the video's size,w/hthe logo's). -
-map 0:a?keeps the audio if there is any. The?stops silent videos from failing. -
-c:a copypasses the audio through untouched, so only the video is re-encoded. -
libx264 -preset veryfast -crf 23is H.264 at the encoder's default quality, tuned for speed, which matters when you pay per millisecond. -
+faststartmoves 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
}));
// 3. In a finally block: delete the temp object and the /tmp work folder
Why this design works:
- The key never changes. Stored keys, public URLs, and presigned GET URLs all keep working.
-
No infinite loop. The final write is a copy, and the function ignores copies. The temporary upload sits outside
uploads/, so it doesn't trigger the function at all. -
Files always display in the browser.
ContentTypecomes from the file type, not from whatever the upload sent. AContent-Disposition: attachmentheader is dropped, because it would make browsers download the file instead of showing it. -
Cleanup always runs. The
finallyblock removes the temp object and/tmp/<uuid>even if processing fails.
The handler processes every record with Promise.allSettled, logs each failure with its key, and throws if any record failed. The failure then shows up in CloudWatch, and Lambda retries it.
Step 7: Check the code before deploying
Make sure Docker Desktop is running, then do three quick checks.
The handler exists:
Test-Path .\app\index.mjs # should print True
The JavaScript parses (no output means no syntax errors):
docker run --rm --platform linux/amd64 `
--mount "type=bind,source=$($PWD.Path)\app,target=/var/task" `
-w /var/task --entrypoint node `
public.ecr.aws/lambda/nodejs:26 `
--check index.mjs
Sharp loads on Lambda's OS:
docker run --rm --platform linux/amd64 `
--mount "type=bind,source=$($PWD.Path)\app,target=/var/task" `
-w /var/task --entrypoint node `
public.ecr.aws/lambda/nodejs:26 `
-e "import('sharp').then(() => console.log('sharp loaded successfully')).catch(e => { console.error(e); process.exit(1) })"
If you don't see sharp loaded successfully, node_modules was probably installed outside the container. Delete it and repeat Step 4.
Step 8: Package and deploy
Create the two ZIP files
The structure inside each ZIP matters more than anything else in this step.
Function ZIP: open the app folder, select everything inside it (not the folder itself), and compress it into aws-media-watermark.zip. index.mjs must sit at the root of the ZIP, or Lambda won't find the handler.
aws-media-watermark.zip
├── index.mjs
├── package.json
└── node_modules/
Layer ZIP: open the ffmpeg-layer folder and compress only the bin folder into aws-ffmpeg-layer.zip.
aws-ffmpeg-layer.zip
└── bin/
└── ffmpeg
Create the layer
In the Lambda console, go to Layers → Create layer:
-
Name:
aws-ffmpeg-layer -
Upload a .zip file:
aws-ffmpeg-layer.zip - Compatible architectures: x86_64
- Compatible runtimes: Node.js 26.x
Click Create.
Upload the code and attach the layer
- Open Event Functions →
aws-media-watermark→ Code. - Click Update → Update from a .zip file and upload
aws-media-watermark.zip. - Under Runtime settings → Edit, confirm the handler is
index.handler: the file isindex.mjs, and it exportshandler. - Scroll to Layers → Edit → Add a layer, choose Custom layers, select
aws-ffmpeg-layerand its version, and click Add, then Save.
Step 9: Test with a manual event
Testing with a hand-made event before connecting the trigger means a bug can't affect real uploads.
- Upload a sample JPEG to the
uploads/folder. Mine wasuploads/wood.jpeg. - On the function's Test tab, click Create new event, name it
WatermarkImageTest, and paste:
{
"Records": [
{
"eventVersion": "2.1",
"eventSource": "aws:s3",
"awsRegion": "eu-north-1",
"eventTime": "2026-11-25T03:00:00.000Z",
"eventName": "ObjectCreated:Put",
"s3": {
"bucket": { "name": "aws-watermark-demo" },
"object": { "key": "uploads/wood.jpeg", "size": 67345 }
}
}
]
}
Only eventName and s3.object.key affect the handler, but the key must match a real object.
- Click Test. My run:
When I opened wood.jpeg again, the watermark was in the bottom-right corner:
| Figure 7a: Before watermarking | Figure 7b: After watermarking |
|
|
Step 10: Connect the S3 trigger
- On the function overview page, click Add trigger and choose S3.
- Select your bucket.
- Under Event types, choose PUT, POST, and Multipart upload completed. Don't choose COPY.
- Set Prefix to
uploads/. - Tick the Recursive invocation acknowledgement and click Add. Lambda adds the permission S3 needs to invoke the function.
About that checkbox: AWS warns you because this function writes to the bucket that triggers it, which is the classic recipe for an infinite loop. This setup has three guards:
- The final write is a copy, and copies aren't subscribed.
- The temporary upload lands outside
uploads/, so it never triggers the function. - Objects marked
watermarked=trueare skipped.
AWS recommends separate input and output buckets. I used one bucket because keeping the original key was a requirement.
Step 11: Upload from the app with a presigned URL
- Use PUT, not a presigned POST form.
-
Include a file extension in the key. The handler falls back to
Content-Type, but an extension is the reliable signal. -
Set
ContentTypeso S3 stores a type the browser can display. -
Not set an ACL. The bucket has ACLs disabled, and the bucket policy already makes
uploads/public.
Backend (Node.js, AWS SDK v3):
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { randomUUID } from "node:crypto";
const s3 = new S3Client({ region: "eu-north-1" });
export async function createUploadUrl(ext, contentType) {
const key = `uploads/${randomUUID()}${ext}`; // e.g. uploads/3f2a….jpg
const url = await getSignedUrl(
s3,
new PutObjectCommand({
Bucket: "aws-watermark-demo",
Key: key,
ContentType: contentType, // e.g. "image/jpeg". No ACL here.
}),
{ expiresIn: 300 }
);
return { url, key };
}
Flutter:
final response = await http.put(
Uri.parse(uploadUrl),
headers: {'Content-Type': 'image/jpeg'}, // must match what was signed
body: await file.readAsBytes(), // raw bytes, not a multipart form
);
Step 12: Test the whole pipeline
Upload through the app, then open Monitor → View CloudWatch logs on the function.
Image: upload a portrait photo from a phone. The log should show Watermarking complete: uploads/<key>, and the public URL should display the image upright, with the watermark, in the browser:
https://aws-watermark-demo.s3.eu-north-1.amazonaws.com/uploads/<key>
Video: upload a short .mp4 and check the watermark, the audio, and playback on a phone. My result:
INFO Watermarking complete: uploads/51328eaa-d0ff-40fd-a62f-cd5c9ac53246gym.mp4
Duration: 12219.98 ms Billed Duration: 12695 ms Memory Size: 1024 MB Max Memory Used: 274 MB Init Duration: 474.36 ms
Step 13: Keep storage in check
Versioning keeps every un-watermarked original as an older version, and each temporary file leaves a version and a delete marker behind. Add a lifecycle rule so these don't pile up:
- Go to Management → Create lifecycle rule and apply it to all objects.
- Choose Permanently delete noncurrent versions of objects and set a number of days (I used 30).
- Choose Delete expired object delete markers or incomplete multipart uploads, and abort incomplete multipart uploads after 7 days.
If you need to keep originals for longer, raise the number of days instead of skipping the rule.
Limitations
-
There's a short window before the watermark lands. For a few seconds (longer for video), the original file is live at its URL. If that matters, upload to a private
incoming/prefix, and have the function copy the result into the publicuploads/folder. -
Formats. Only
.jpg,.jpeg,.png,.webp, and.mp4are handled. iPhones often produce.heicphotos and.movvideos; convert them in the app or extend the handler. - Video logo size is fixed at 250 px, so it looks small on 4K video and large on very small video.
Wrapping up
The core idea is small: S3 tells Lambda a file has arrived, Lambda processes it, and the result goes back in place at the same key. Most of the work was in the details:
The full code is on GitHub. If you build something similar, or find a better answer to any of the limitations above, tell me in the comments.
Further reading
- Using AWS Lambda with Amazon S3
- Amazon S3 event notifications and the event message structure
- Controlling object ownership and disabling ACLs
- Uploading objects with presigned URLs
- Managing Lambda dependencies with layers
- Building Lambda functions with Node.js
- Sharp: composite
- FFmpeg overlay filter
ffmpeg-staticon npm







Top comments (0)