Your Lambda Function URL returns 403? Build a $0 serverless URL shortener the 2026 way
Your Lambda Function URL returns 403? Build a $0 serverless URL shortener the 2026 way
Your Lambda Function URL returns 403? Build a $0 serverless URL shortener the 2026 way
One Lambda, one DynamoDB table, no API Gateway, zero servers, and the one permission most tutorials forget.
I followed a 2024 tutorial to give a Lambda function a public URL. Everything deployed fine. Then I ran
curl and got this:{"Message":"Forbidden. For troubleshooting Function URL authorization issues, see: ..."}The tutorial wasn't wrong when it was written. AWS changed the rules in October 2025: new Lambda function URLs now need two permissions in the function's resource policy,
lambda:InvokeFunctionUrl and lambda:InvokeFunction . Older guides only add the first one, so anything you build from them today returns 403 .In this article we'll build something useful while fixing it: a working URL shortener (
POST a long URL, get a short one back, open it, get redirected). It runs entirely on services with an Always Free allowance, so for a learning project it should cost $0.[YOUR NOTE: one line on why you built this, e.g. "I wanted short links for my portfolio projects"] What we're building
curl -X POST ──► Lambda Function URL ──► Lambda (Python) ──► DynamoDB browser GET /abc1234 ──► same Lambda ──► 301 redirect to the long URL- Lambda Function URL: a built-in HTTPS endpoint for one function. No API Gateway needed.
- Lambda (Python 3.13, arm64): creates codes and handles redirects.
- DynamoDB: stores
code → url. We use provisioned capacity of 1 read / 1 write unit so we stay inside the Always Free allowance (on-demand mode bills per request).
Prerequisites
- An AWS account (the new Free plan works)
- AWS CLI v2 configured (
aws configureoraws login)
-
zipandcurl
Set a few variables we'll reuse:
export AWS_REGION=eu-west-1 # use your regionexport ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)export TABLE=short-linksexport FN=url-shortenerStep 1 — Create the DynamoDB table
aws dynamodb create-table \ --table-name $TABLE \ --attribute-definitions AttributeName=code,AttributeType=S \ --key-schema AttributeName=code,KeyType=HASH \ --provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1One partition key,
code , and nothing else. DynamoDB is schemaless, so the url attribute doesn't need declaring.Step 2 — Create a least-privilege IAM role
The function needs to write logs and read/write only this table. Nothing more.
cat > trust.json <<'EOF'{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" }]}EOF
cat > table-access.json <<EOF{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["dynamodb:PutItem", "dynamodb:GetItem"], "Resource": "arn:aws:dynamodb:${AWS_REGION}:${ACCOUNT_ID}:table/${TABLE}" }]}EOF
aws iam create-role --role-name ${FN}-role \ --assume-role-policy-document file://trust.json
aws iam attach-role-policy --role-name ${FN}-role \ --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
aws iam put-role-policy --role-name ${FN}-role \ --policy-name table-access --policy-document file://table-access.jsonNotice the second heredoc uses
<<EOF (no quotes) so the shell fills in your region and account ID.Step 3 — Write the function
Save this as
app.py :import base64import jsonimport osimport secretsimport stringfrom urllib.parse import urlparse
import boto3from botocore.exceptions import ClientError
TABLE = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])ALPHABET = string.ascii_letters + string.digits
def _response(status, body=None, headers=None): return { "statusCode": status, "headers": {"Content-Type": "application/json", **(headers or {})}, "body": json.dumps(body) if body is not None else "", }
def _create(event): raw = event.get("body") or "{}" if event.get("isBase64Encoded"): raw = base64.b64decode(raw).decode() try: url = json.loads(raw).get("url", "") except json.JSONDecodeError: return _response(400, {"error": "Body must be JSON"})
parsed = urlparse(url) if parsed.scheme not in ("http", "https") or not parsed.netloc: return _response(400, {"error": "Send {\"url\": \"https://...\"}"})
for _ in range(5): # retry on the (very unlikely) code collision code = "".join(secrets.choice(ALPHABET) for _ in range(7)) try: TABLE.put_item( Item={"code": code, "url": url}, ConditionExpression="attribute_not_exists(code)", ) host = event["headers"].get("host", "") return _response(201, {"short": f"https://{host}/{code}", "code": code}) except ClientError as e: if e.response["Error"]["Code"] != "ConditionalCheckFailedException": raise return _response(500, {"error": "Could not generate a unique code"})
def _redirect(code): item = TABLE.get_item(Key={"code": code}).get("Item") if not item: return _response(404, {"error": "Not found"}) return _response(301, headers={"Location": item["url"]})
def handler(event, context): method = event["requestContext"]["http"]["method"] path = event.get("rawPath", "/").strip("/")
if method == "POST" and path == "": return _create(event) if method == "GET" and path: return _redirect(path) return _response(405, {"error": "POST / to create, GET /<code> to follow"})Three details worth calling out:
-
secrets, notrandom: codes come from a cryptographically secure generator, so nobody can guess the next one.
-
ConditionExpression="attribute_not_exists(code)": DynamoDB refuses to overwrite an existing code. 62⁷ ≈ 3.5 trillion combinations makes a collision extremely rare, but this guarantees it can never silently replace someone else's link.
- Scheme check: only
http/httpsare accepted, so nobody can store ajavascript:link and turn your domain into a phishing tool.
Step 4 — Deploy it
zip function.zip app.py
sleep 10 # give IAM a moment to propagate the new role
aws lambda create-function \ --function-name $FN \ --runtime python3.13 \ --architectures arm64 \ --handler app.handler \ --role arn:aws:iam::${ACCOUNT_ID}:role/${FN}-role \ --zip-file fileb://function.zip \ --environment Variables={TABLE_NAME=$TABLE}boto3 is already in the Lambda Python runtime, so no dependencies need packaging. arm64 (Graviton) is cheaper per millisecond than x86 and works the same for pure Python.If you get "The role defined for the function cannot be assumed by Lambda", IAM hasn't finished propagating. Wait a few seconds and run it again.
Step 5 — Create the URL (and hit the 403)
aws lambda create-function-url-config \ --function-name $FN --auth-type NONE \ --query FunctionUrl --output textThe console does the next part for you, but with the CLI you add the permission yourself. Here's what most older tutorials show:
aws lambda add-permission \ --function-name $FN \ --statement-id public-url \ --action lambda:InvokeFunctionUrl \ --principal "*" \ --function-url-auth-type NONETry it:
export URL=$(aws lambda get-function-url-config --function-name $FN --query FunctionUrl --output text)curl -i -X POST $URL -H 'content-type: application/json' -d '{"url":"https://aws.amazon.com"}'→
HTTP/1.1 403 Forbidden .[YOUR NOTE: how long this took you to figure out] Step 6 — The fix: the second permission
Since October 2025, new function URLs need
lambda:InvokeFunction as well. Add it, scoped so it only applies to calls coming through the function URL:aws lambda add-permission \ --function-name $FN \ --statement-id public-url-invoke \ --action lambda:InvokeFunction \ --principal "*" \ --invoked-via-function-urlThat
--invoked-via-function-url flag matters. Without it, you'd be granting everyone permission to invoke your function by any method, not just through the URL. With it, the statement gets a lambda:InvokedViaFunctionUrl = true condition.You can check both statements are there:
aws lambda get-policy --function-name $FN --query Policy --output text | python3 -m json.toolIf you use CloudFormation/SAM/CDK: the same rule applies. In plain CloudFormation, that's a second
AWS::Lambda::Permission with Action: lambda:InvokeFunction , Principal: "*" and InvokedViaFunctionUrl: true .Step 7 — Test it
# create a short linkcurl -s -X POST $URL -H 'content-type: application/json' \ -d '{"url":"https://aws.amazon.com/free/"}'# {"short": "https://xxxx.lambda-url.eu-west-1.on.aws/Q7bZ2kd", "code": "Q7bZ2kd"}
# follow itcurl -i ${URL}Q7bZ2kd# HTTP/1.1 301 Moved Permanently# location: https://aws.amazon.com/free/
# bad input is rejectedcurl -s -X POST $URL -d '{"url":"javascript:alert(1)"}'# {"error": "Send {\"url\": \"https://...\"}"}Paste the short link into your browser: you land on the AWS Free Tier page. 🎉
[YOUR SCREENSHOT: your terminal showing the 201 and the 301] What does it cost?
For a hobby project, nothing. Lambda's Always Free allowance is 1 million requests and 400,000 GB-seconds per month, and our table uses 1 RCU / 1 WCU, well inside DynamoDB's 25/25 Always Free capacity. There's no API Gateway to pay for, because the Function URL is built in.
Still, set an AWS Budget alert (Billing → Budgets → Use a template → Zero spend budget). On the new Free plan, creating a budget is one of the activities that earns you extra credits.
Before you share the link publicly
This is a learning project. A public
NONE -auth endpoint can be called by anyone, so before you post it anywhere:- Cap the blast radius: if your account's concurrency limit allows it, set reserved concurrency (
aws lambda put-function-concurrency --function-name $FN --reserved-concurrent-executions 5).
- Add a TTL on the table so old links expire and storage never grows.
- Go further: put CloudFront + AWS WAF in front for rate limiting, or switch to
AWS_IAMauth for private use.
Clean up
aws lambda delete-function-url-config --function-name $FNaws lambda delete-function --function-name $FNaws iam delete-role-policy --role-name ${FN}-role --policy-name table-accessaws iam detach-role-policy --role-name ${FN}-role \ --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRoleaws iam delete-role --role-name ${FN}-roleaws dynamodb delete-table --table-name $TABLEWhat I learned
- If a tutorial is more than a year old, check the docs first. AWS ships constantly, and security defaults change.
- A 403 from a Function URL is almost always the resource policy, not your code.
get-policyis the first thing to run.
- Least privilege is easy when you start with it: two DynamoDB actions on one table ARN.
Over to you: have you hit the Function URL 403? And what would you add next: click counting, custom aliases, or link expiry? Tell me in the comments and I'll build the most-voted one in my next article. 👇
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article