Claude Code AWS Lambda practical guide: Node.js, IAM और API Gateway
Claude Code से Node.js Lambda बनाएं: local test, least-privilege IAM, environment variables, API Gateway और logs.
Claude Code AWS Lambda के लिए बहुत तेज़ workflow देता है। एक ही context में handler, test event, IAM policy draft, deploy commands और review checklist तैयार हो सकते हैं। लेकिन AWS permissions और cost production decisions हैं। Claude Code से draft और review करवाएं, पर IAM permission देना, public API खोलना या billable resource बनाना बिना human approval के safe नहीं है।
यह guide team workflow के हिसाब से लिखा गया है: Node.js Lambda बनाना, local test चलाना, IAM को least privilege के करीब रखना, environment variables set करना, API Gateway जोड़ना, CloudWatch Logs पढ़ना, zip package update करना और safe review loop चलाना। Lambda को सरल भाषा में event आने पर चलने वाला छोटा runtime समझें। IAM वह permission table है जो तय करता है कि function क्या कर सकता है। API Gateway HTTP request को Lambda तक पहुंचाने वाला entry point है।
काम शुरू करने से पहले official references खोलकर रखें: AWS Lambda getting started, Lambda with Node.js, Lambda environment variables, CloudWatch Logs monitoring, और Claude Code common workflows। इस article के examples 1 जून 2026 के हिसाब से Node.js 24 Lambda runtime use करते हैं।
कब यह pattern सही है
Lambda तब अच्छा है जब आपको छोटा और reliable काम करना है, लेकिन पूरे दिन server चलाने की जरूरत नहीं है। Claude Code तब सबसे ज्यादा मदद करता है जब काम structured हो और final decision reviewer के पास रहे।
| Use case | Lambda क्यों ठीक है | Claude Code क्या draft करे | Human review क्या देखे |
|---|---|---|---|
| Webhook receiver | Payment, form और SaaS events छोटे होते हैं | Signature check, event fixture, failure response | Secrets, retry, duplicate event |
| Internal JSON API | छोटे endpoints के लिए permanent server नहीं चाहिए | Handler, API Gateway commands, log format | Auth, CORS, exposure, cost |
| Batch entry point | CSV, image job, notification छोटे से शुरू हो सकते हैं | Input validation, structured logs, error classes | Timeout, retry strategy, safe deletion |
पहले proof of concept के लिए AWS CLI और zip package तेज़ है। Team operation के लिए बाद में वही logic SAM, CDK या किसी reviewed IaC flow में ले जाएं।
| Method | Best for | सावधानी |
|---|---|---|
| AWS Console | एक बार behavior देखना | Manual steps review history में साफ नहीं रहते |
| AWS CLI + zip | छोटा reproducible proof | IAM और env vars ध्यान से review करने होंगे |
| SAM / CDK | Long-term team workflow | IaC review और deploy approval जरूरी होंगे |
flowchart LR
A[Claude Code draft] --> B[Local Node.js test]
B --> C[Human IAM और environment review]
C --> D[Zip package dev में deploy]
D --> E[API Gateway से test]
E --> F[CloudWatch Logs पढ़ें]
F --> A
1. Node.js Lambda handler बनाएं
सबसे पहले बिना external dependency वाला index.mjs बनाते हैं। यह HTTP API v2 events और पुराने REST API event format दोनों को handle करता है।
// index.mjs
import crypto from "node:crypto";
const allowedStages = new Set(["dev", "staging", "prod"]);
function readConfig() {
const stage = process.env.APP_STAGE ?? "dev";
if (!allowedStages.has(stage)) {
throw new Error(`Invalid APP_STAGE: ${stage}`);
}
return {
stage,
tableName: process.env.TABLE_NAME ?? "local-orders",
logLevel: process.env.LOG_LEVEL ?? "info",
};
}
function log(level, message, details = {}) {
console.log(
JSON.stringify({
level,
message,
service: "orders-api",
...details,
})
);
}
function json(statusCode, body) {
return {
statusCode,
headers: {
"content-type": "application/json",
},
body: JSON.stringify(body),
};
}
function parseBody(event) {
if (!event.body) return {};
const raw = event.isBase64Encoded
? Buffer.from(event.body, "base64").toString("utf8")
: event.body;
return JSON.parse(raw);
}
export async function handler(event = {}, context = {}) {
const config = readConfig();
const method = event.requestContext?.http?.method ?? event.httpMethod ?? "GET";
const path = event.rawPath ?? event.path ?? "/";
const requestId = context.awsRequestId ?? "local";
log("info", "request.start", {
requestId,
method,
path,
stage: config.stage,
});
try {
if (method === "GET" && path === "/health") {
return json(200, { ok: true, stage: config.stage });
}
if (method === "POST" && path === "/orders") {
const payload = parseBody(event);
const orderId = payload.orderId ?? crypto.randomUUID();
log("info", "order.accepted", {
requestId,
orderId,
tableName: config.tableName,
});
return json(202, {
orderId,
status: "accepted",
storedIn: config.tableName,
});
}
return json(404, { error: "not_found", method, path });
} catch (error) {
log("error", "request.failed", {
requestId,
errorName: error.name,
errorMessage: error.message,
});
return json(500, { error: "internal_error", requestId });
}
}
यह version अभी DynamoDB में write नहीं करता। ऐसा जानबूझकर है। Beginner workflow में पहले event receive करना, JSON parse करना, valid response देना और searchable logs बनाना verify करें। Database और extra permissions बाद में जोड़ें।
2. Event fixture से local test करें
Fixture fixed test input है। Claude Code से generate करवाएं, लेकिन repo में रखें ताकि reviewer वही input चलाकर result देख सके।
{
"version": "2.0",
"routeKey": "POST /orders",
"rawPath": "/orders",
"requestContext": {
"http": {
"method": "POST",
"path": "/orders"
}
},
"headers": {
"content-type": "application/json"
},
"body": "{\"orderId\":\"demo-1001\",\"amount\":3200,\"currency\":\"JPY\"}",
"isBase64Encoded": false
}
इसे events/create-order.json में save करें और local runner जोड़ें।
// local-test.mjs
import { readFile } from "node:fs/promises";
import { handler } from "./index.mjs";
process.env.APP_STAGE = "dev";
process.env.TABLE_NAME = "orders-dev";
process.env.LOG_LEVEL = "debug";
const eventPath = process.argv[2] ?? "events/create-order.json";
const event = JSON.parse(await readFile(eventPath, "utf8"));
const result = await handler(event, { awsRequestId: "local-001" });
console.log(JSON.stringify(result, null, 2));
AWS touch करने से पहले run करें:
node local-test.mjs events/create-order.json
अगर local result में statusCode: 202 नहीं है, तो deploy करने से debugging धीमी होगी। Concrete fixture Claude Code को भी guess करने के बजाय real failing input पर reason करने देता है।
3. IAM को least privilege के करीब रखें
Lambda execution role में AdministratorAccess attach न करें। Logs से शुरू करें और data access तभी जोड़ें जब handler सच में उसका use करे।
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "CreateOwnLogGroupIfMissing",
"Effect": "Allow",
"Action": "logs:CreateLogGroup",
"Resource": "arn:aws:logs:ap-northeast-1:123456789012:*"
},
{
"Sid": "WriteOwnLambdaLogs",
"Effect": "Allow",
"Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
"Resource": "arn:aws:logs:ap-northeast-1:123456789012:log-group:/aws/lambda/claude-orders-dev:*"
},
{
"Sid": "ReadWriteOnlyOrdersTable",
"Effect": "Allow",
"Action": ["dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:Query"],
"Resource": "arn:aws:dynamodb:ap-northeast-1:123456789012:table/orders-dev"
}
]
}
यह JSON production answer नहीं, draft है। Account, region, function name और table name बदलें। जब तक DynamoDB सच में use नहीं हो रहा, DynamoDB block हटाएं। Permission review के लिए AWS IAM guide भी देखें।
4. AWS CLI से zip package deploy करें
नीचे के commands real AWS resources बनाते हैं और cost generate कर सकते हैं। Dev account use करें, region confirm करें और cleanup steps पहले समझें।
export AWS_REGION=ap-northeast-1
export FUNCTION_NAME=claude-orders-dev
export ROLE_NAME=claude-orders-dev-lambda-role
export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
zip function.zip index.mjs
Lambda को role assume करने देने के लिए trust-policy.json बनाएं।
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
ऊपर वाला IAM draft lambda-policy.json में save करें, फिर role और function बनाएं।
aws iam create-role \
--role-name "$ROLE_NAME" \
--assume-role-policy-document file://trust-policy.json
aws iam put-role-policy \
--role-name "$ROLE_NAME" \
--policy-name claude-orders-dev-inline \
--policy-document file://lambda-policy.json
ROLE_ARN=$(aws iam get-role \
--role-name "$ROLE_NAME" \
--query "Role.Arn" \
--output text)
aws lambda create-function \
--function-name "$FUNCTION_NAME" \
--runtime nodejs24.x \
--handler index.handler \
--zip-file fileb://function.zip \
--role "$ROLE_ARN" \
--architectures arm64 \
--timeout 10 \
--memory-size 128 \
--environment "Variables={APP_STAGE=dev,TABLE_NAME=orders-dev,LOG_LEVEL=info}" \
--region "$AWS_REGION"
सिर्फ code update करना हो तो function recreate न करें।
zip function.zip index.mjs
aws lambda update-function-code \
--function-name "$FUNCTION_NAME" \
--zip-file fileb://function.zip \
--region "$AWS_REGION"
Environment variables update करते समय ध्यान रखें। update-function-configuration में Variables देने पर पूरा map replace होता है। पहले current configuration पढ़ें, फिर change करें। Passwords और API keys को plain environment variables में रखने के बजाय Secrets Manager या Parameter Store consider करें।
aws lambda update-function-configuration \
--function-name "$FUNCTION_NAME" \
--environment "Variables={APP_STAGE=dev,TABLE_NAME=orders-dev,LOG_LEVEL=debug}" \
--region "$AWS_REGION"
5. API Gateway और CloudWatch Logs verify करें
पहले Lambda को directly invoke करें।
aws lambda invoke \
--function-name "$FUNCTION_NAME" \
--payload fileb://events/create-order.json \
--region "$AWS_REGION" \
response.json
cat response.json
फिर HTTP API बनाएं। इससे public endpoint बनेगा, इसलिए auth, CORS, rate limit और deletion plan पहले review करें।
API_ID=$(aws apigatewayv2 create-api \
--name claude-orders-dev-api \
--protocol-type HTTP \
--target "arn:aws:lambda:${AWS_REGION}:${ACCOUNT_ID}:function:${FUNCTION_NAME}" \
--query "ApiId" \
--output text)
aws lambda add-permission \
--function-name "$FUNCTION_NAME" \
--statement-id AllowHttpApiInvoke \
--action lambda:InvokeFunction \
--principal apigateway.amazonaws.com \
--source-arn "arn:aws:execute-api:${AWS_REGION}:${ACCOUNT_ID}:${API_ID}/*/*" \
--region "$AWS_REGION"
API_ENDPOINT=$(aws apigatewayv2 get-api \
--api-id "$API_ID" \
--query "ApiEndpoint" \
--output text)
curl -s "$API_ENDPOINT/health"
curl -s -X POST "$API_ENDPOINT/orders" \
-H "content-type: application/json" \
-d '{"amount":3200,"currency":"JPY"}'
Test के तुरंत बाद logs पढ़ें।
aws logs tail "/aws/lambda/${FUNCTION_NAME}" \
--follow \
--region "$AWS_REGION"
Logs न दिखें तो region, function name, logs:CreateLogStream और logs:PutLogEvents check करें। API Gateway 500 दे तो Lambda response में statusCode, headers और body हैं या नहीं देखें। आगे के लिए AWS CloudWatch guide और AWS API Gateway guide पढ़ें।
Lambda review के लिए Claude prompt
Claude Code को edit या deploy से पहले risk explain करने दें।
You are reviewing a Node.js AWS Lambda change for a team repository.
Scope:
- Files: index.mjs, events/*.json, IAM policy JSON, deployment commands in docs
- Runtime: nodejs24.x
- Entry point: index.handler
Review for:
1. API Gateway event compatibility and response shape
2. Input validation and JSON parsing failures
3. Environment variables that overwrite existing values
4. IAM actions that are wider than needed
5. CloudWatch logs that expose secrets or personal data
6. AWS resources that can create unexpected cost
7. Local test commands that a reviewer can copy and run
Return:
- blocking issues
- non-blocking improvements
- exact commands to verify locally
- questions a human must answer before deploying
Safe loop है: explore, plan, edit, local test, केवल dev deploy, logs inspect, फिर IAM और cost changes के लिए human approval। इस CLI proof of concept को CI/CD और IaC में ले जाने के लिए AWS deployment guide देखें।
Common pitfalls
पहली गलती local reproduction के बिना deploy करना है। Event shape गलत हो तो fixture CloudWatch से जल्दी पकड़ता है।
दूसरी गलती secrets को environment variables में direct रखना है। Environment variables config के लिए ठीक हैं, लेकिन secrets को access control और rotation चाहिए।
तीसरी गलती IAM बहुत wide देना है। dynamodb:* और Resource: "*" demo पास करा देते हैं, पर गलती की impact range भी बढ़ाते हैं।
चौथी गलती API Gateway endpoint को owner के बिना public करना है। URL share करने से पहले auth, CORS, throttling, logging और cleanup date तय करें।
पांचवीं गलती cost ignore करना है। Lambda छोटा दिखता है, पर API Gateway, CloudWatch Logs, DynamoDB, NAT और external API calls charge कर सकते हैं।
ClaudeCodeLab इस तरह के workflow को Claude Code templates and training material में organize करता है। अगर आपकी team real repository के साथ AWS permissions, CLAUDE.md, review prompts और deploy approval rules design करना चाहती है, तो Claude Code consultation and training देखें।
Proof-of-concept resources काम खत्म होने पर delete करें।
aws apigatewayv2 delete-api --api-id "$API_ID" --region "$AWS_REGION"
aws lambda delete-function --function-name "$FUNCTION_NAME" --region "$AWS_REGION"
aws iam delete-role-policy --role-name "$ROLE_NAME" --policy-name claude-orders-dev-inline
aws iam delete-role --role-name "$ROLE_NAME"
इस article का workflow वास्तव में चलाने पर सबसे बड़ा फायदा यह दिखा कि Claude Code handler, fixture, IAM draft और CLI commands को एक reviewable context में रखता है। Risk code generation में कम और permissions तथा public exposure decisions में ज्यादा है। Reliable pattern है: पहले local fixture, फिर dev deploy, फिर CloudWatch evidence, और production से पहले IAM तथा cost पर human review।
मुफ़्त PDF: Claude Code cheatsheet
Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.
हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.
लेखक के बारे में
Masa
Claude Code workflow और team adoption पर काम करने वाला engineer.
संबंधित लेख
Claude Code Obsidian to CLAUDE.md workflow: context बार-बार न समझाएं
Obsidian notes को CLAUDE.md operating notes में बदलकर Claude Code sessions को resume करना आसान बनाएं.
Claude Code Revenue CTA Routing: article से PDF, Gumroad और consultation तक
Reader intent के आधार पर free PDF, Gumroad products और consultation तक CTA route करने वाला workflow.
Claude Code टीम हैंडऑफ नियम: review proof, permissions, rollback और revenue path
Claude Code टीम काम के लिए evidence, permission rules, rollback, free PDF, Gumroad और consultation path वाला handoff.