Cloud and deployment · Intermediate · 25 min
Share private S3 files safely with presigned URLs
By Padding · Updated 18 Nov 2026
Debian (node:26 image) and Ubuntu 26.04 · Node.js 26.13.1 · AWS CLI 2.42.4 · AWS SDK for JavaScript 3.1178.0 · Python 3.15 with boto3 1.44.12
You will keep an S3 bucket private and still let browsers download and upload files through short-lived presigned URLs, with type and size limits, CORS and logs that never hold a working link.
On this page
Most apps end up storing files people should not see without permission: invoices, ID scans, profile photos, exports. The safe default is a bucket nobody can read from the internet. The question is how a browser gets one file out of it, or puts one in, without your server streaming every byte or handing out AWS keys.
A presigned URL is the answer. Your server, which holds AWS credentials, signs a URL for one action on one object (download reports/report.txt, or upload to uploads/<id>.png) that works for a few minutes. Anyone holding the URL can use it until it expires. That makes it a bearer token, like a password in a link, and most of this tutorial is about keeping that power small.
You will build it end to end: a private bucket, a download link from the AWS CLI, a small Node.js 26 service that signs upload links with a fixed content type and exact size, a bucket CORS rule so a web page can upload directly, the same download link from Python with boto3, and logs that never contain a working URL. Everything lives in ~/presign-demo and in one bucket named presign-demo-<your account ID>, which you delete at the end. Storage for a few small files costs next to nothing, but it is billed until you clean up.
Step 1 · Install the tools and create a private bucket
Install curl, unzip and jq, then version 2.42.4 of the AWS CLI from Amazon's versioned installer. uname -m prints x86_64 or aarch64, which matches Amazon's file names:
sudo apt update
sudo apt install -y curl unzip jq ca-certificates
AWS_CLI_VERSION=2.42.4
cd "$(mktemp -d)"
curl -fsSLo awscliv2.zip "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m)-${AWS_CLI_VERSION}.zip"
unzip -q -o awscliv2.zip
sudo ./aws/install
aws --versionIf the AWS CLI is already installed, run sudo ./aws/install --update instead. It does not get updates from apt; to upgrade later, run the same commands with a newer version number.
Point the CLI at your sandbox account (export AWS_PROFILE=<your-sandbox-profile> if you use a named profile; replace the placeholder) and pick a Region. The commands below use London, eu-west-2; Cape Town is af-south-1, but it is an opt-in Region you have to enable in the account first. The Node.js SDK reads AWS_REGION and the CLI and boto3 read AWS_DEFAULT_REGION, so set both. Then create the working folder, the bucket and one private file:
export AWS_REGION=eu-west-2 AWS_DEFAULT_REGION=eu-west-2
mkdir -p ~/presign-demo
cd ~/presign-demo
export BUCKET="presign-demo-$(aws sts get-caller-identity --query Account --output text)"
aws s3 mb "s3://$BUCKET"
echo "Quarterly figures, draft 3" > report.txt
aws s3 cp report.txt "s3://$BUCKET/reports/report.txt"
aws s3 ls "s3://$BUCKET" --recursiveNew buckets have Block Public Access turned on and ACLs disabled, so nothing in this bucket is public unless someone changes that. Confirm it, and confirm that an anonymous request is refused:
aws s3api get-public-access-block --bucket "$BUCKET"
curl -s -o /dev/null -w '%{http_code}\n' "https://$BUCKET.s3.$AWS_REGION.amazonaws.com/reports/report.txt"Check it worked
aws --version starts with aws-cli/2.42.4. aws s3 ls lists reports/report.txt with a size of 27 bytes. get-public-access-block shows all four settings as true, and the anonymous curl prints 403.
Step 2 · Share a download link from the AWS CLI
aws s3 presign signs a GET URL on your machine. It does not call AWS, so it succeeds even for a key that does not exist; the check happens when someone uses the link. Sign one for 10 minutes and use it as a stranger would, with plain curl and no credentials:
cd ~/presign-demo
URL=$(aws s3 presign "s3://$BUCKET/reports/report.txt" --expires-in 600)
echo "$URL"
curl -fsS "$URL"Always quote the URL. It contains &, which the shell would otherwise treat as "run in the background".
Read the query string. X-Amz-Credential names the access key that signed it, X-Amz-Date is when, X-Amz-Expires is how many seconds it lasts, and X-Amz-Signature is what proves it. Change one character of the path or the query and S3 rejects it. When the time runs out, the same link answers 403 with Request has expired:
SHORT=$(aws s3 presign "s3://$BUCKET/reports/report.txt" --expires-in 5)
sleep 10
curl -sS "$SHORT"Three rules decide how long a link really lives:
- The default is 3600 seconds and the most the CLI and SDKs allow is 604800 (7 days). The S3 console allows 1 minute to 12 hours.
- A link signed with temporary credentials dies when those credentials do, whatever
--expires-insays. Ifaws sts get-caller-identityshows an ARN withassumed-role, as it does for SSO users, Lambda functions, ECS tasks and EC2 instance roles, your 7-day link stops working when the session ends, often within 1 to 12 hours. For a long-lived link you would need long-lived keys, which is usually the wrong trade. Sign a short link when it is needed instead. - S3 checks the expiry when a request starts. A large download that began in time finishes even if the expiry passes halfway, but a resumed download after the expiry fails. On slow or prepaid mobile connections, which are common for users in Lagos or Nairobi, give the user a fresh link when they retry rather than one long expiry up front.
Check it worked
curl prints Quarterly figures, draft 3, and the URL contains X-Amz-Expires=600. In your sandbox account, the 5-second link prints an AccessDenied error containing Request has expired.
Step 3 · Write a Node.js service that signs upload links
For uploads, the browser should send the file straight to S3, but only a file your app agreed to. The service below accepts a file type and size, refuses anything outside the rules, and signs a PUT URL for a key it chooses itself, so a user cannot overwrite someone else's file by picking a name. A presigned PUT replaces any object already at that key, which is another reason to generate the key on the server.
Install the S3 client and the presigner at exact versions:
cd ~/presign-demo
npm init -y > /dev/null
npm install @aws-sdk/client-s3@3.1178.0 @aws-sdk/s3-request-presigner@3.1178.0Create server.mjs:
cd ~/presign-demo
cat > server.mjs <<'JS'
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
import { S3Client, PutObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
const BUCKET = process.env.BUCKET;
const PORT = Number(process.env.PORT ?? 8080);
const MAX_BYTES = 5 * 1024 * 1024;
const TYPES = { 'image/png': 'png', 'image/jpeg': 'jpg', 'application/pdf': 'pdf' };
const UPLOAD_SECONDS = 300;
const DOWNLOAD_SECONDS = 60;
if (!BUCKET) throw new Error('Set BUCKET to your bucket name');
// Region and credentials come from the environment or your AWS profile.
// WHEN_REQUIRED stops the SDK adding a checksum of an empty body to PUT URLs.
const s3 = new S3Client({
requestChecksumCalculation: 'WHEN_REQUIRED',
responseChecksumValidation: 'WHEN_REQUIRED',
});
function send(res, status, body) {
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
res.end(JSON.stringify(body));
}
async function readJson(req) {
let raw = '';
for await (const chunk of req) {
raw += chunk;
if (raw.length > 10_000) return null;
}
try {
return JSON.parse(raw);
} catch {
return null;
}
}
async function createUpload(req, res) {
const body = await readJson(req);
if (!body) return send(res, 400, { error: 'Send a JSON body' });
const ext = TYPES[body.type];
if (!ext) return send(res, 400, { error: 'Only PNG, JPEG and PDF files are allowed' });
if (!Number.isInteger(body.size) || body.size < 1 || body.size > MAX_BYTES)
return send(res, 400, { error: 'Files must be between 1 byte and 5 MB' });
const key = `uploads/${randomUUID()}.${ext}`;
const command = new PutObjectCommand({
Bucket: BUCKET,
Key: key,
ContentType: body.type,
ContentLength: body.size,
});
const url = await getSignedUrl(s3, command, {
expiresIn: UPLOAD_SECONDS,
signableHeaders: new Set(['content-type', 'content-length']),
});
// Log what was issued, never the URL itself.
console.log(`upload url issued key=${key} type=${body.type} size=${body.size}`);
send(res, 200, { key, url, expiresIn: UPLOAD_SECONDS });
}
async function download(res, key) {
if (!/^uploads\/[0-9a-f-]{36}\.(png|jpg|pdf)$/.test(key)) return send(res, 404, { error: 'Not found' });
const url = await getSignedUrl(s3, new GetObjectCommand({ Bucket: BUCKET, Key: key }), {
expiresIn: DOWNLOAD_SECONDS,
});
console.log(`download url issued key=${key}`);
res.writeHead(302, { location: url, 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' });
res.end();
}
createServer(async (req, res) => {
const { pathname, searchParams } = new URL(req.url, 'http://localhost');
try {
if (req.method === 'GET' && pathname === '/') {
const page = await readFile(new URL('./upload.html', import.meta.url));
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'referrer-policy': 'no-referrer' });
return res.end(page);
}
if (req.method === 'POST' && pathname === '/uploads') return await createUpload(req, res);
if (req.method === 'GET' && pathname === '/download') return await download(res, searchParams.get('key') ?? '');
send(res, 404, { error: 'Not found' });
} catch (err) {
console.error(`request failed: ${req.method} ${pathname}: ${err.name}`);
send(res, 500, { error: 'Something went wrong' });
}
}).listen(PORT, () => console.log(`Listening on http://localhost:${PORT}`));
JS
printf 'BUCKET=%s\nAWS_REGION=%s\n' "$BUCKET" "$AWS_REGION" > .env
node --check server.mjsThe lines that matter:
ContentTypeandContentLengthgo into the signature, so the upload must send exactly thatContent-Typeheader and exactly that many bytes. A bigger file, or a script renamed to.pngand sent astext/html, fails withSignatureDoesNotMatch. The JavaScript presigner leavescontent-typeout of the signature unless you list it insignableHeaders; without that line, any content type would be accepted.requestChecksumCalculation: 'WHEN_REQUIRED'matters for PUT URLs. With the SDK's default setting, version 3.1178.0 addsx-amz-checksum-crc32for an empty body to the URL, and a real upload then fails its checksum.- The service picks the key, logs the key and never logs a URL.
.envholds the bucket name and Region only. Credentials stay in your AWS profile or environment, never in the file.
This endpoint signs for anyone who can reach it. In your app, put /uploads and /download behind your login and check that the signed-in user may see the key before you sign a download. If you need a size range instead of an exact size, S3's presigned POST with a content-length-range condition does that; the PUT approach here is simpler and covers most single-file uploads.
Check it worked
npm install lists both packages with no errors, node --check prints nothing, and cat .env shows your bucket name and eu-west-2.
Step 4 · Request an upload link and use it with curl
Start the service in its own terminal and leave it running. If you opened a new terminal, cd ~/presign-demo first; the profile or credentials you use for AWS must be set there too:
cd ~/presign-demo
node --env-file=.env server.mjsBack in your first terminal, make a 2 KB stand-in for a photo, ask the service for an upload link, and send the file to S3 with it:
cd ~/presign-demo
head -c 2048 /dev/urandom > sample.png
SIZE=$(wc -c < sample.png | tr -d ' ')
RESPONSE=$(curl -fsS -X POST http://localhost:8080/uploads \
-H 'content-type: application/json' \
-d "{\"type\":\"image/png\",\"size\":$SIZE}")
KEY=$(echo "$RESPONSE" | jq -r .key)
UPLOAD_URL=$(echo "$RESPONSE" | jq -r .url)
echo "$KEY"
curl -fsS -X PUT -H 'content-type: image/png' --data-binary @sample.png "$UPLOAD_URL"
aws s3api head-object --bucket "$BUCKET" --key "$KEY" --query '[ContentType,ContentLength]' --output textNow ask for something the rules forbid. The service refuses a 20 MB file before it signs anything:
curl -sS -X POST http://localhost:8080/uploads \
-H 'content-type: application/json' \
-d '{"type":"image/png","size":20000000}'And S3 refuses a valid link used with a different content type, because the signature no longer matches the request:
curl -sS -X PUT -H 'content-type: text/html' --data-binary @sample.png "$UPLOAD_URL"Finally, download the file the way a user would, through the service's /download redirect to a 60-second link:
curl -fsSL -o downloaded.png "http://localhost:8080/download?key=$KEY"
cmp downloaded.png sample.png && echo "same file"Check it worked
head-object prints image/png and 2048. The 20 MB request answers {"error":"Files must be between 1 byte and 5 MB"}. The text/html upload returns XML with SignatureDoesNotMatch. The download ends with same file. In the upload URL, X-Amz-SignedHeaders=content-length%3Bcontent-type%3Bhost shows the three headers S3 will insist on.
Step 5 · Let your web page upload with a CORS rule
curl does not care which site it runs on. A browser does: a page on http://localhost:8080 that sends a PUT with a Content-Type: image/png header to the S3 endpoint is a cross-origin request, so the browser first sends a preflight OPTIONS request and only continues if S3 answers that this origin may do it. The answer comes from the bucket's CORS configuration.
Allow exactly one origin, one method and the one header the page sends. Replace http://localhost:8080 with your site's origin (for example https://app.example.com) when you deploy. Downloads through the redirect are ordinary page navigations, which CORS does not apply to, so GET is not needed here:
cd ~/presign-demo
cat > cors.json <<'JSON'
{
"CORSRules": [
{
"AllowedOrigins": ["http://localhost:8080"],
"AllowedMethods": ["PUT"],
"AllowedHeaders": ["content-type"],
"ExposeHeaders": ["ETag"],
"MaxAgeSeconds": 600
}
]
}
JSON
aws s3api put-bucket-cors --bucket "$BUCKET" --cors-configuration file://cors.json
aws s3api get-bucket-cors --bucket "$BUCKET"Ask S3 the browser's question yourself, once from your origin and once from another site:
curl -sS -o /dev/null -D - -X OPTIONS "$UPLOAD_URL" \
-H 'Origin: http://localhost:8080' \
-H 'Access-Control-Request-Method: PUT' \
-H 'Access-Control-Request-Headers: content-type' | tee preflight-ok.txt
curl -sS -o /dev/null -D - -X OPTIONS "$UPLOAD_URL" \
-H 'Origin: https://other-site.example' \
-H 'Access-Control-Request-Method: PUT' | tee preflight-other.txtCORS only decides which web pages may make the request from a browser. It does not protect the bucket: the presigned signature and your login do that.
Check it worked
get-bucket-cors prints your one rule. The first preflight includes Access-Control-Allow-Origin: http://localhost:8080 and Access-Control-Allow-Methods: PUT. The second answers 403 with no Access-Control-Allow-Origin header.
Step 6 · Upload from a browser page
Create upload.html next to the server. The service reads it on every request, so there is no need to restart. The page asks your service for a link, then sends the file to S3 itself; the file never passes through your server:
cd ~/presign-demo
cat > upload.html <<'HTML'
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Upload a file</title>
<h1>Upload a file</h1>
<form id="form">
<label for="file">PNG, JPEG or PDF, up to 5 MB</label>
<input id="file" name="file" type="file" accept="image/png,image/jpeg,application/pdf" required>
<button>Upload</button>
</form>
<p id="status" role="status"></p>
<script type="module">
const form = document.getElementById('form');
const status = document.getElementById('status');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const file = document.getElementById('file').files[0];
try {
status.textContent = 'Asking for an upload link';
const res = await fetch('/uploads', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ type: file.type, size: file.size }),
});
const body = await res.json();
if (!res.ok) {
status.textContent = body.error;
return;
}
status.textContent = 'Uploading';
const put = await fetch(body.url, { method: 'PUT', headers: { 'content-type': file.type }, body: file });
if (!put.ok) {
status.textContent = `Upload failed (${put.status}). Try again.`;
return;
}
const link = document.createElement('a');
link.href = `/download?key=${encodeURIComponent(body.key)}`;
link.textContent = 'Download it';
status.replaceChildren(`Uploaded ${body.key}. `, link);
} catch {
status.textContent = 'Upload failed. Check your connection and try again.';
}
});
</script>
</html>
HTML
curl -fsS http://localhost:8080/ | grep -F '<title>Upload a file</title>'The browser sets Content-Length from the file itself, so it always matches the size the page reported. If the user picks a different file between the two requests, the signature fails and they try again with a new link. The catch-all message matters on flaky mobile data: a dropped connection should leave the user with something to do, not a frozen button.
Open http://localhost:8080 in your browser, choose a small PNG or PDF and press Upload. Then try a file over 5 MB.
Check it worked
The status line reads Uploaded uploads/<a long id>.png. Download it, and the link opens or saves your file. The large file shows Files must be between 1 byte and 5 MB without uploading anything. aws s3 ls "s3://$BUCKET/uploads/" now lists two objects: the one from curl and the one from the browser. If the browser console shows a CORS error instead, check that the origin in cors.json matches the address bar exactly, including the port.
Step 7 · Sign the same download link from Python
If your backend is Python, boto3 signs links the same way. Install uv 0.13.10 with its official installer; it can fetch Python 3.15 for you and run a script with boto3 without a separate virtual environment. uv is not managed by apt; upgrade it later with uv self update:
curl -LsSf https://astral.sh/uv/0.13.10/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
uv --versionCreate presign.py. It signs a 5-minute download link for a key you pass in and asks S3 to send the file as an attachment, so the browser saves it rather than opening it:
cd ~/presign-demo
cat > presign.py <<'PY'
import os
import sys
import boto3
s3 = boto3.client("s3")
url = s3.generate_presigned_url(
"get_object",
Params={
"Bucket": os.environ["BUCKET"],
"Key": sys.argv[1],
"ResponseContentDisposition": "attachment",
},
ExpiresIn=300,
)
print(url)
PY
PY_URL=$(uv run --quiet --python 3.15 --with boto3==1.44.12 presign.py "$KEY")
curl -fsS -D headers.txt -o from-python.png "$PY_URL"
cmp from-python.png sample.png && echo "same file"
grep -i '^content-disposition' headers.txtFor uploads, generate_presigned_url("put_object", Params={"Bucket": ..., "Key": ..., "ContentType": "image/png", "ContentLength": 2048}, ExpiresIn=300) signs both headers, just like the Node.js service.
Check it worked
uv --version prints uv 0.13.10. The script prints a URL with X-Amz-Expires=300 and response-content-disposition=attachment, the download ends with same file, and headers.txt contains Content-Disposition: attachment.
Step 8 · Keep working links out of logs
A presigned URL in a log file is a working key for as long as it lasts, readable by everyone who can read that log. Look at the service's terminal: it printed lines like upload url issued key=uploads/....png type=image/png size=2048 and download url issued key=..., never a URL. That is deliberate, and worth keeping as the code grows:
- Your app's logs and error tracker. Log the key, the user and the expiry, never the URL or a whole response body that contains it. Error trackers often capture request and response data automatically; check what yours sends.
- Request logs. The service logs
pathname, notreq.url. In general, a log line that records full URLs with query strings will record signatures one day. S3's own server access logs record the full request URI, so restrict who can read that log bucket and redact query strings before sharing log lines. - Referrers and history. The upload page and the redirect send
Referrer-Policy: no-referrer, so a page the user visits next is not told the URL. Links also end up in browser history and chat apps, which is one more reason to keep expiries short. - Audit by signer instead. CloudTrail data events and S3 access logs show which credentials signed a request, not which of your users received the link. Record "user X was given key Y until time Z" in your own app when you sign it.
If a link does leak, you cannot cancel one link on its own. Deleting or rotating the credentials that signed it, or adding a bucket policy that denies requests using the s3:signatureAge condition, stops it before the expiry.
Check it worked
Search what the service printed for a signature: X-Amz-Signature does not appear anywhere in its terminal output, and every issued line names a key.
Step 9 · Clean up
Stop the service with Ctrl+C in its terminal. The next command deletes every object in the bucket and then the bucket itself; check that $BUCKET still says presign-demo-<your account ID> before you run it:
echo "$BUCKET"
aws s3 rb "s3://$BUCKET" --force
cd ~
rm -rf ~/presign-demouv keeps the Python 3.15 it downloaded under ~/.local/share/uv. If you do not use it elsewhere, remove it with uv python uninstall 3.15.
Check it worked
aws s3api head-bucket --bucket "$BUCKET" fails with a 404 or 403 error, and ~/presign-demo is gone. Any links you signed for that bucket now fail as well.
Next steps
- Make sure nothing else can make the bucket public: lock down an S3 bucket with a bucket policy.
- Give the signing service its own role that can only touch
uploads/*: create an IAM role with a least-privilege policy. - Sign with short-lived credentials on your laptop too: set up the AWS CLI with SSO and named profiles.
- Learn what preflights and allowlists do for your own APIs: configure CORS for an API.
Related tutorials
- Write, test and deploy an AWS Lambda function in Node.jsYou will have a tested Node.js 26 function running on AWS Lambda with its own logs-only role, tuned memory, timeout and environment variables, and a published version behind a live alias you can move forward or roll back.
- Understand AWS VPCs: subnets, route tables, gateways and NATYou will have built a two-zone VPC with public and private subnets, an internet gateway, a NAT gateway and a free S3 endpoint using the AWS CLI, read every route table to see which subnets are public and why, and then deleted it all.
- Set up the AWS CLI v2 with IAM Identity Center sign-in and named profilesYou will have AWS CLI 2.42.4 installed from a signature-checked bundle, signing in through IAM Identity Center with separate dev and prod profiles and no long-lived access keys on your machine.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials