AWS Builder Center
The Serverless SaaS Frontend Recipe: From Sign-In to Scale

The Serverless SaaS Frontend Recipe: From Sign-In to Scale

How a Next.js frontend uses identity, API Gateway, Lambda, DynamoDB, signed payment events and CDK without giving database access to the browser

In this request path, frontend code runs in two execution environments:
  • the browser, which renders the interface and starts requests; and
  • the Next.js server runtime, which can verify a session and call protected services.
The distinction matters because a customer controls their browser. Identity, service credentials and database permissions must not rely on unverified client input.
This article follows the implemented account-data request. It is not a claim that every route in the application already uses the same path: a few other Next.js server routes still call DynamoDB through the AWS SDK. Those calls remain server-side, but moving them behind the backend API would produce one consistent service, IAM and observability boundary. The backend would still need real request authorization in addition to its API key.
The code excerpts are abridged from the current implementation. Omitted fields do not change the request or security flow.

Architecture at a glance
Layer
Responsibility
Boundary or caveat
Browser
UI state, user actions and same-origin requests
Service secrets, trusted identity or database permissions
Next.js on Amplify
Session checks, input shaping and server-to-server calls
Final entitlement or payment truth
Identity provider
Authentication, sessions and stable user identity
Product entitlement
API Gateway
Backend routing, API-key requirement and best-effort throttling
Customer authorization by API key alone
Lambda
Validation, business rules and state transitions
Shared unrestricted IAM
DynamoDB
License, team, trial, webhook and operational state
Client-side access
Payment provider + webhook Lambda
Checkout and signed billing events
Browser-declared payment success
EventBridge + lifecycle Lambda
Time-based work
Page-request latency
S3
Installer bytes
Current objects are public; private files would need signed access
CloudWatch + SNS
Metrics, alarms and operator notifications
Detection based only on returned HTTP status
CDK
Reviewable backend infrastructure definitions
Resources that remain manually managed
This division is the architecture. “Serverless” describes how the responsibilities run; it does not remove them.

1. Establish identity before reading account data

In steps 1–2 the browser signs in with the identity provider and receives a session. In step 3 it calls an application-owned route; it does not send an email address, API key or DynamoDB key.
const response = await fetch("/api/user-data", {
method: "GET",
headers: { "Content-Type": "application/json" },
});

const data = await response.json();
if (response.ok && data.success) {
setUserData(data.userData);
}
In step 4 the Next.js route reads the session and resolves the current user. Clerk's  auth()  exposes the authenticated session claims, while  currentUser()  fetches the current Backend User and counts against Clerk's Backend API rate limit. The route therefore selects only the primary email it needs instead of returning the full user object. See Clerk's   currentUser()  documentation .
const { userId } = await auth();
if (!userId) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}

const user = await currentUser();
const email = user?.primaryEmailAddress?.emailAddress
?.trim()
.toLowerCase();
Problem solved: the browser cannot choose the email used by this account-data lookup.
There is an important limit. The extra ownership check only helps when the DynamoDB row already contains a  clerkId :
if (licenseData.clerkId && licenseData.clerkId !== userId) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
Rows without  clerkId  still rely on the verified primary email. The stronger long-term model is to backfill the stable, provider-assigned user ID and use it as the ownership key or a lookup index.

2. Let the server create the backend request

In step 5 the route calls API Gateway with an API URL and key that are unavailable to browser JavaScript.
const upstream = await fetch(
`${apiUrl}/license?email=${encodeURIComponent(email)}`,
{
headers: { "x-api-key": apiKey },
cache: "no-store",
signal: AbortSignal.timeout(10_000),
},
);
The complete route also:
  • fails closed when  LICENSE_API_URL  or  LICENSE_API_KEY  is missing;
  • disables response caching for current entitlement data;
  • bounds the upstream wait to ten seconds;
  • maps an unreachable or timed-out backend to  502 ; and
  • rejects a successful upstream response that is not a JSON object.
The current backend request places the email in the URL query string. URLs can appear in access logs and tracing systems, so an opaque provider-assigned user ID—or a body field on a non-GET operation with deliberate log redaction—is safer for personally identifiable data.
The downloads page retries the account request up to three times with a one-second delay. Retrying transient network errors and  502 / 503  responses is useful; retrying deterministic  400 ,  401  or  403  responses only adds load and delays the correct UI. A small status-aware retry helper would make that resilience intentional.
These server-only values are copied into  .env.production  by the Amplify build specification because Next.js SSR does not receive Amplify build variables automatically. That behavior matches  AWS's SSR environment-variable guidance .
However, AWS also warns that deployment-artifact readers can inspect values written into those files. IAM roles or a runtime secret store are stronger choices for AWS credentials and high-value secrets.  NEXT_PUBLIC_  variables must never contain secrets because Next.js intentionally includes them in browser bundles.
This account-data route does not need the DynamoDB region or AWS credentials. Other existing server routes that call DynamoDB directly use a server-only helper with the region fixed to  ap-south-1  and optional  DYNAMO_*  credentials. Prefer an Amplify SSR compute role over long-lived access keys, then migrate those routes behind the backend API.

3. Separate traffic management from user authorization

Steps 5–7 pass through API Gateway, Lambda and DynamoDB. CDK connects the operation and grants this reader Lambda table-read permissions.
const getLicenseFn = new nodejs.NodejsFunction(this, "GetLicenseFn", {
entry: path.join(__dirname, "../src/handlers/get-license.ts"),
handler: "handler",
...commonLambdaProps,
});

table.grantReadData(getLicenseFn);

licenseResource.addMethod(
"GET",
new apigateway.LambdaIntegration(getLicenseFn),
{ apiKeyRequired: true },
);
The shared usage plan targets 10 requests per second with a burst of 20:
const plan = api.addUsagePlan("UsagePlan", {
name: "Standard",
throttle: { rateLimit: 10, burstLimit: 20 },
});
An API key is not customer authentication or authorization. AWS explicitly says not to use API keys for that purpose, and usage-plan throttles are best-effort rather than hard cost controls. See  API Gateway usage plans and API keys .
The current key is useful for identifying and throttling the server client, but a leaked key could call email-addressed routes directly. A production hardening step is to add IAM authorization, a JWT/Lambda authorizer, or signed server-to-server requests. Broad CORS settings do not replace authorization.

4. Keep entitlement rules on the backend

The reader Lambda performs a DynamoDB  GetItem , computes effective access at the current server time, and returns an explicit field list instead of serializing the raw item.
const licenseData = unmarshall(Item);
const effective = computeEffectiveStatus(licenseData as any, Date.now());

const safeData = {
email: licenseData.email,
paid: licenseData.paid || false,
machines: Array.isArray(licenseData.machines) ? licenseData.machines : [],
effectiveActive: effective.active,
inGrace: effective.inGrace,
effectiveReason: effective.reason,
};
Problems solved: the server remains the source of truth for trials, revocation and grace periods; the browser can consume computed flags without reproducing the decision tree; and an explicit response object limits accidental field exposure. The desktop client deliberately mirrors the logic for offline checks, but the server answer wins on revalidation. The real response includes additional license and billing fields, so that allowlist still needs a data-sensitivity review whenever it changes.
Step 8 returns JSON through the same Lambda, API Gateway and Next.js path. The browser never receives DynamoDB permissions.

5. Apply the same boundary to mutations

A write requires more than changing  GET  to  POST . The machine-deregistration route demonstrates the intended pattern:
  1. Read the signed-in user from the server session.
  1. Validate the browser-supplied machine ID.
  1. Fetch the account row and reject a conflicting  clerkId  when present.
  1. Send the server-derived email and validated machine ID to the backend.
  1. Let a write-enabled Lambda update DynamoDB.
const machineId = body?.machineId;
if (typeof machineId !== "string" || !machineId.trim()) {
return NextResponse.json({ error: "Missing machineId" }, { status: 400 });
}

const upstream = await fetch(`${apiUrl}/license/deregister`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": apiKey,
},
body: JSON.stringify({ email, machineId: machineId.trim() }),
signal: AbortSignal.timeout(10_000),
});
CDK gives the deregistration Lambda read/write access while the account reader remains read-only. This is a useful IAM split, but authorization still depends on the Next.js caller behaving correctly because API Gateway only checks the shared API key.
The current Lambda reads the machine array, removes one value in memory and writes the complete array back. Two simultaneous mutations could overwrite each other. A production-strength version should use optimistic locking with a version condition, or redesign machine registrations as separate items so each removal is an independent conditional delete.
The codebase is still hybrid. At least five Next.js API route files currently instantiate a DynamoDB client for payment polling, team membership or billing operations, and a server-rendered unsubscribe page also accesses the table. They are server-side—not browser access—but they bypass the single API boundary. Converging them behind authorized backend operations would simplify IAM, logging and business-rule ownership.

6. Separate checkout commands from payment facts

Checkout creation is a command: the browser asks the Next.js server to create a hosted checkout, and the server calls the payment provider using a secret bearer token. The route validates the plan, constrains team-seat quantities, requires a signed-in identity for team ownership, whitelists legacy product IDs and strips reserved routing metadata supplied by the browser.

Follow P1–P12 from top to bottom. The diagram intentionally shows the current direct DynamoDB read in the payment-status SSR route.
if (tier !== undefined) {
if (!isLicenseTier(tier)) {
return NextResponse.json({ error: "Invalid tier" }, { status: 400 });
}
}

if (tier === "team" && !clerkEmail) {
return NextResponse.json(
{ error: "Team checkout requires a signed-in account." },
{ status: 401 },
);
}

const resp = await fetch(`${baseUrl}/checkouts`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(payload),
});
For signed-in team purchases, the account email comes from the identity session. Solo and magic-link checkout paths may use a validated email supplied in the request, so those flows do not have the same identity guarantee and must rely on the intended magic-link trust model.
The provider returns a checkout URL for browser redirection. That response means only that checkout was created—not that money moved.
A successful browser redirect is not proof of payment. The payment provider calls a public Lambda Function URL in step 9, and the Lambda fetches its verification secret from Secrets Manager in step 10.

The URL is configured with  AuthType.NONE ; this integration uses the provider's HMAC signature rather than AWS IAM. It is publicly reachable, and trust begins only after signature verification. Its CORS configuration does not authenticate the webhook.
The handler verifies the exact request body before parsing it:
const rawBody = event.body
? event.isBase64Encoded
? Buffer.from(event.body, "base64").toString("utf8")
: event.body
: "";

const verification = verifyWebhookSignature(
rawBody,
{ id: webhookId, signature: webhookSignature, timestamp: webhookTimestamp },
webhookSecret,
);

if (!verification.ok) {
return jsonResponse(401, { error: "Invalid signature" });
}
The handler then checks a DynamoDB ledger keyed by webhook ID. A previously processed event is acknowledged without reapplying it; an event previously skipped by the product gate remains eligible for redelivery.
const ledger = unmarshall(existingLedger.Item);
if (ledger.skipped !== true) {
return jsonResponse(200, { status: "duplicate" });
}

await dispatch(evt, eventId, eventTs);
After dispatch, it writes the ledger entry on a best-effort basis. A second safeguard uses a conditional update on  lastWebhookEventId , protecting license and team state writes if two deliveries race or the ledger write fails. The handler compares  webhook-timestamp  with  lastWebhookTs  for payment and subscription paths. Refund processing instead checks row existence and subscription identity; dispute branches do not apply the timestamp guard.
Problems solved in steps 9–11: invalid signatures are rejected, sequential duplicates are acknowledged, duplicate state updates are conditionally blocked, failed dispatch remains retryable, stale payment/subscription events are guarded, and foreign products are prevented from changing license or team state.
This is not full exactly-once processing. In a concurrent race, a duplicate conditional state write can be rejected after both invocations observed the same earlier row, while a later best-effort side effect such as a purchase email can still run twice. Returning an “applied” result from the conditional update—or claiming the event atomically before external side effects—would close that gap.
The return page closes the asynchronous UX loop without becoming a writer. It treats the provider's redirect status as a hint, then polls a read-only  /api/payment-success  route every two seconds initially and every five seconds after 30 seconds, for up to ten minutes. The webhook can finish even if the customer closes the tab.
const resp = await fetch("/api/payment-success", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
signal: controller.signal,
});

if (!resp.ok) return false;
const data = await resp.json();
if (data?.status === "paid" && data?.userData?.paid) {
setPhase("succeeded");
}
That poller currently reads DynamoDB directly from a Next.js server route. It requires a session, but it accepts the email from the request body and only rejects an ownership mismatch when the stored row contains  clerkId . It should derive email server-side like  /api/user-data  or use the stable user ID before the direct-DynamoDB routes are retired.

7. Keep scheduled work outside page latency

EventBridge schedules the lifecycle worker with  rate(1 hour)  in step 12. A rate expression starts when the rule is created; it does not mean “at the top of every hour.” AWS now describes scheduled rules as a legacy option and recommends EventBridge Scheduler for richer retry and retention controls. See  EventBridge schedule patterns .
new events.Rule(this, "LifecycleEmailsHourlySchedule", {
schedule: events.Schedule.rate(cdk.Duration.hours(1)),
targets: [new eventsTargets.LambdaFunction(lifecycleCronFn)],
});
In steps 13–14 the worker scans current DynamoDB state and calls the email provider. After a successful send, it records the message kind on the row to suppress later repeats.
The send and marker write are not atomic. If delivery succeeds but the DynamoDB update fails, a later run can send the message again. The current mechanism is duplicate suppression, not an exactly-once guarantee.
The scan is simple but reads across the table even when a filter excludes most rows. As the dataset grows, a lifecycle-due index or time-bucketed work queue will be more predictable and less expensive.
The current email helper reads  RESEND_API_KEY  from the Lambda environment. Although CDK also binds a Secrets Manager name, the worker does not currently fetch that secret at runtime. The diagram therefore shows Secrets Manager only for the webhook path. Moving email delivery to runtime secret retrieval would remove this transitional split.

8. Send public binaries directly from S3

In step 15 the browser navigates to hardcoded S3 object URLs for each installer. Those objects must be publicly readable for the documented anonymous-download flow. Next.js and Lambda do not relay the file bytes.
const link = document.createElement("a");
link.href = downloadLink;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
This removes application compute from the download path. It also means access is public and release filenames are coupled to the page deployment. Use a release manifest or stable redirect for version management. If downloads become private, generate a short-lived presigned URL; AWS documents that pattern under  S3 presigned URLs .
The current regional S3 URLs do not add an application CDN or branded download domain. If global download latency, cache control or origin shielding becomes material, place CloudFront in front of the bucket; private distribution can use signed URLs or cookies instead of making the S3 objects public.

9. Be exact about what the alarms detect

In step 16 Lambda sends service metrics to CloudWatch, and function logs go to CloudWatch Logs when the execution role permits it. CDK creates  metricErrors()  alarms for selected critical functions and routes alarm state to SNS in step 17. After the email subscription is confirmed, SNS can deliver those notifications in step 18.
const alarm = new cloudwatch.Alarm(this, name, {
metric: fn.metricErrors({ period }),
threshold,
evaluationPeriods: 1,
treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
});

alarm.addAlarmAction(new cwActions.SnsAction(alertTopic));
This detects unhandled Lambda invocation errors and timeouts. It does not necessarily detect a handler that catches an error and returns HTTP  500 , because the invocation itself completed normally. It also does not detect email-send errors that the lifecycle worker catches and logs as warnings.
To cover those application failures, emit a custom metric, create CloudWatch Logs metric filters, or deliberately aggregate and throw after safe per-item processing. AWS defines the  Errors  metric in  Lambda metrics . The SNS email endpoint must also be confirmed before notifications are delivered, as described in  SNS email subscription setup .
The account route creates a short request ID and returns it with errors, which is useful for support. It does not currently forward that ID to API Gateway or Lambda, so it is not yet an end-to-end correlation ID. Forwarding an  x-request-id , logging structured fields and redacting customer emails would connect the frontend and backend traces without turning logs into a second customer database.

10. Treat runtime configuration as architecture

The frontend and backend are joined by configuration:
  •  LICENSE_API_URL  selects the API Gateway stage.
  •  LICENSE_API_KEY  identifies the server client to its usage plan.
  •  DYNAMO_*  values support the remaining direct-DynamoDB SSR routes.
  •  REGION  and  TABLE_NAME  are injected into backend Lambdas by CDK.
  • Payment and email credentials are consumed only by server runtimes.
The Amplify build specification copies selected variables into the file Next.js recognizes for production SSR:
preBuild:
commands:
- npm ci --legacy-peer-deps
- printenv | grep -E '^(NEXT_PUBLIC_|CLERK_|LICENSE_|DYNAMO_|AWS_REGION=)' > .env.production
This is operationally necessary for the present hosting setup, but it is not a secret vault. Values written into build artifacts should be treated as readable by anyone who can access those artifacts. Use an Amplify compute role for AWS access, prefer runtime secret retrieval for provider credentials, rotate the shared API key and ensure secret values never use a  NEXT_PUBLIC_  prefix.
Configuration should also fail visibly. The account route returns  500  when its backend URL or key is absent instead of silently falling back to another table or region. That behavior helped turn an ambiguous “DynamoDB problem” into the correct diagnosis: the frontend communicates through an API, so its first dependencies are the SSR environment and API endpoint—not the DynamoDB SDK.

11. Know exactly what CDK owns

Step 19 represents the backend deployment. The current CDK stack imports an existing DynamoDB table by name and defines its Lambda functions, API Gateway methods, IAM grants, schedules, Secrets Manager bindings, CloudWatch alarms and SNS topic. It does not currently provision the Amplify application, and the public installer bucket is outside this backend stack.
Because the table is imported, this template does not define its billing mode, encryption choice, point-in-time recovery, deletion protection or TTL configuration. Those live settings belong in the deployment audit—or in a separate owning stack—not in assumptions made by application code.
Most functions have operation-specific DynamoDB grants. One webhook function also has a temporary  actions: ["*"]  and  resources: ["*"]  role policy added as a Secrets Manager workaround. That exception defeats least privilege and should be replaced with only  secretsmanager:GetSecretValue  and  secretsmanager:DescribeSecret  on the exact secret ARN patterns already produced by the scoped  bindSecret  helper.
CDK synthesis confirms the boundary: the backend template contains 18 Lambda functions, one REST API, one hourly EventBridge rule, six CloudWatch alarms, one SNS topic and one unauthenticated Lambda Function URL. It defines no DynamoDB table because the table is imported. Synthesis proves what CloudFormation would deploy; it does not prove that the intended account currently runs that template.

12. Understand the scaling and cost model

The synchronous account path scales horizontally through Amplify, API Gateway and Lambda, while DynamoDB distributes item access by partition key. The first intentional ceiling is the shared API usage plan at 10 requests per second with a burst of 20. Because every server request uses the same key, that budget is shared across customers and will need adjustment or per-client isolation as traffic grows.
The main cost and scale pressure points are straightforward:
  • Identity calls:  currentUser()  consumes identity-provider Backend API capacity. Cache or use session claims when the full user record is unnecessary.
  • API and Lambda calls: every account-data read becomes a Next.js invocation, an API Gateway request and a Lambda invocation.
  • DynamoDB reads: point reads are efficient; hourly scans grow with the whole table, even with filter expressions.
  • Downloads: direct S3 delivery removes Lambda cost but still incurs object requests and internet data transfer.
  • Logs: verbose application logs—especially those containing customer identifiers—create cost and privacy retention obligations.
  • Webhook ledger rows:  expiresAt  only causes automatic cleanup if DynamoDB TTL is enabled on that attribute; that live table setting must be verified separately.
The table mixes license rows with prefixed trial, team, webhook, rate-limit, audit and alias records. This single-table model can be efficient, but every scan and access pattern must deliberately exclude unrelated entity types. As scheduled work grows, use an index or time-bucketed queue for records that are due instead of scanning the shared table.
The current direct-DynamoDB frontend helper is fixed to  ap-south-1 , while backend Lambdas receive their stack Region through  REGION . The diagrams do not claim cross-Region failover. Define recovery objectives before adding complexity. At minimum, verify DynamoDB recovery settings and preserve installer artifacts independently; add cross-Region replication only if the required recovery time and recovery point justify it.

13. Test the contracts, not only the functions

The important tests follow trust boundaries and failure modes:
  • no session returns  401 ;
  • a mismatched stored user ID returns  403 ;
  • missing runtime configuration returns  500 ;
  • backend timeouts and invalid payloads return  502 ;
  • after an authorizer is added, an API request without valid authorization is rejected;
  • invalid, duplicate, stale and concurrently delivered webhooks do not corrupt state;
  • a successful provider side effect followed by a failed marker write is safely recoverable;
  • returned application errors emit an observable metric;
  • synthesized IAM contains no wildcard exception; and
  • every published installer URL returns the expected status, content type and checksum.
The current automated backend suite compiles, but its single infrastructure test does not exercise these flows. Before calling the architecture production-complete, add route tests, handler tests with DynamoDB condition failures, webhook concurrency tests, CDK assertions and a small post-deployment smoke test. Use  cdk diff  for review,  cdk synth  as a policy gate and deployment checks for SNS confirmation, TTL, API stages and runtime secrets.

Production priorities

Priority
Change
Why it comes now
Immediate
Remove the webhook Lambda's wildcard IAM policy
It defeats the otherwise useful least-privilege design
Immediate
Add IAM, JWT or Lambda-authorizer protection to API Gateway
The shared API key is not authorization
Immediate
Derive ownership from a stable user ID on every route
Email-based ownership and optional  clerkId  checks leave legacy gaps
Immediate
Emit metrics for handled application failures
Current alarms can miss returned  500  responses and caught provider errors
Next
Move direct-DynamoDB SSR routes behind the backend
One service boundary is easier to secure and observe
Next
Make webhook and email side effects idempotent
Conditional state writes alone do not guarantee exactly-once external effects
At growth
Replace lifecycle scans with indexed due work
Scan cost grows with the whole mixed-entity table
At growth
Replace hardcoded installer URLs with a release manifest or stable redirect
Releases should not require editing UI handlers
The architecture does not need to be replaced. Its managed-service decomposition is sound; the remaining work is to finish authorization, consistency and failure detection across every route.

The audited recipe

  • Treat the browser as untrusted and derive identity from the server session.
  • Prefer a stable identity-provider ID over email as the durable owner key.
  • Keep browser code away from database credentials.
  • Treat API keys and usage plans as client identification and best-effort throttling, not authorization.
  • Put business rules behind focused Lambda functions and explicit response fields.
  • Trust signed, idempotent webhooks—not browser redirects—for payment state.
  • Run scheduled work outside page requests and make retries idempotent.
  • Send public files directly from object storage; use presigned URLs for private files.
  • Monitor application failures explicitly instead of assuming every HTTP  500  increments Lambda  Errors .
  • Review the synthesized IAM policy and remove wildcard exceptions.
  • Use CDK for the backend resources it actually owns, and document manually managed infrastructure separately.
Serverless does not remove the backend. It makes every trust boundary, event, permission and failure mode more important to name precisely.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article