Skip to content

SvelteKit Adapter AWS: Framework Meets Cloud

Why I built my own SvelteKit adapter for AWS and what the translation between the framework build and Lambda, S3 and CloudFront reveals about both sides.

≈ 10 min readSoftwareAWSCloud

SvelteKit Adapter AWS: Framework Meets Cloud

When a framework’s deployment model and the target platform do not fit together, projects always produce the same by-product: a handwritten deploy script. It copies build output into an S3 bucket, zips up a Lambda handler somewhere, sets cache headers by hand and finally invalidates a CloudFront distribution. That works – until the framework changes the structure of its build output, until a header is forgotten or until the one person who can still explain the script leaves the project. After that, the team has a deployment nobody trusts anymore, and every release becomes a test of courage.

This is exactly where SvelteKit applications that are supposed to run on AWS stand at the beginning of 2022. SvelteKit itself is still in beta – version 1.0 has been announced but not released – and it brings a remarkably clear concept for this problem: adapters. There is adapter-node for your own server, adapter-static for purely static sites, adapter-vercel and adapter-netlify for the respective platforms. There is no official adapter for AWS. So I wrote one: sveltekit-adapter-aws, an open source project that rolls out a SvelteKit app to Lambda, S3 and CloudFront via the AWS CDK. While building it, I noticed a few things about both sides – about the framework and about the cloud. That is what this post is about.

Adapters are an architecture boundary#

At its core, a SvelteKit adapter is a Node module with a single essential function: adapt(). After the actual build, SvelteKit calls this function and passes a builder object through which the adapter picks up the build output: the client code for the browser, the server code for rendering, the prerendered pages. What the adapter does with it is up to the adapter. adapter-node builds a startable HTTP server, adapter-static a directory structure for any web server, adapter-vercel exactly the format the Vercel platform expects.

This boundary is drawn deliberately. The framework knows how routes, components and endpoints become an application. It does not know – and does not want to know – where this application will run later. Everything platform-specific moves behind the adapter interface. For the user, the decision comes down to one line in svelte.config.js:

import { adapter } from 'sveltekit-adapter-aws';
import preprocess from 'svelte-preprocess';

export default {
  preprocess: preprocess(),
  kit: {
    adapter: adapter({
      autoDeploy: true,
      FQDN: 'demo.example.com',
      MEMORY_SIZE: 256,
      LOG_RETENTION_DAYS: 7,
    }),
  },
};

With autoDeploy: true, the build step rolls out the application directly – svelte-kit build then ends not with a directory but with a running CloudFormation stack. That is convenient for prototypes and small projects; for everything else, you can plug in your own CDK app via cdkProjectPath that uses the adapter output as a building block.

Why there was no AWS adapter#

The fact that Vercel and Netlify have their own adapters and AWS does not is neither a coincidence nor an oversight. Vercel and Netlify are platforms: they control both sides of the interface and can define exactly which artifact they expect. AWS is not a platform in this sense but a construction kit. There is no single service called “SvelteKit hosting,” but dozens of primitives from which you assemble one of many possible deployments.

An AWS adapter therefore has to do something the platform adapters do not: define an architecture. Which service answers SSR requests? Where do the static files live? Who distributes the traffic? These are decisions that an architect would otherwise make in a design document – here they live in an npm package. That is exactly what makes such an adapter an interesting piece of software: it is solidified architecture, versioned and reusable.

The architecture: three services, one application#

The split I chose follows the character of the build output. A built SvelteKit app falls into two fundamentally different parts: static files (client bundles, assets, prerendered pages) that can be cached at will, and a server part that has to compute per request. Static content belongs in S3, dynamic content in a Lambda function, and in front of both sits CloudFront as the shared entry point that decides by path where a request goes.

flowchart LR
  B[Browser] --> CF[CloudFront<br/>distribution]
  CF -->|/_app/*, assets,<br/>prerendered pages| S3[S3 bucket<br/>static files]
  CF -->|all other<br/>requests| GW[API Gateway<br/>HTTP API]
  GW --> L[Lambda<br/>SvelteKit SSR]
  R53[Route 53 + ACM<br/>custom domain] -.-> CF

The whole thing is provisioned with the AWS CDK, specifically version 2, which only became generally available in December 2021 – so the project builds on a fairly fresh foundation. Above all, CDK v2 cleans up the package chaos of v1: one library, aws-cdk-lib, instead of dozens of individually versioned modules. For an adapter that travels into other people’s projects as an npm dependency, that is a noticeable difference, because version conflicts between CDK subpackages were a constant issue in v1. The core of the stack, slightly shortened:

import { Stack, StackProps, Duration } from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { RetentionDays } from 'aws-cdk-lib/aws-logs';

export class AWSAdapterStack extends Stack {
  constructor(scope: Construct, id: string, props: StackProps) {
    super(scope, id, props);

    const serverHandler = new lambda.Function(this, 'ServerFunction', {
      runtime: lambda.Runtime.NODEJS_14_X,
      handler: 'index.handler',
      code: lambda.Code.fromAsset(process.env.SERVER_PATH!),
      memorySize: parseInt(process.env.MEMORY_SIZE ?? '128'),
      timeout: Duration.seconds(15),
      logRetention: RetentionDays.ONE_WEEK,
    });
    // ... HTTP API, S3 bucket, CloudFront distribution, Route 53 records
  }
}

A detail that is easy to miss: log retention is deliberately set to seven days. CloudWatch logs without a retention rule grow without limit, and with an SSR function that logs every page request, that adds up faster than you think. In my experience, such operational defaults belong in the adapter, not on a wiki page with recommendations.

From the Lambda event to the framework response#

The actual translation work happens in two places. The first is the build: the server part of the SvelteKit output is bundled with esbuild into a single CommonJS file – format cjs, target Node 14, with the built-in Node modules kept external. Lambda thus gets an artifact without a node_modules directory, which has done package size and cold starts good. The second place is the runtime itself: a small handler shim receives the event from API Gateway, shapes it into the request structure the SvelteKit server expects and translates the response back:

// index.js – bridges API Gateway events to the SvelteKit server
import { init, render } from './app.js';

init();

export async function handler(event) {
  const { rawPath, rawQueryString, headers, requestContext } = event;

  const response = await render({
    method: requestContext.http.method,
    path: rawPath,
    query: new URLSearchParams(rawQueryString),
    headers,
    rawBody: event.body
      ? Buffer.from(event.body, event.isBase64Encoded ? 'base64' : 'utf8')
      : undefined,
  });

  return {
    statusCode: response.status,
    headers: response.headers,
    body: response.body,
  };
}

This shim is unspectacular, but it is the place where the framework world and the cloud world actually meet. This is where it is decided whether binary data is passed through correctly, whether multiple Set-Cookie headers survive and whether query parameters with special characters arrive intact. I did not design any of these small things at my desk; I added each one after a concrete misbehavior. The entire flow from source code to stack looks like this:

flowchart LR
  SRC[SvelteKit<br/>source code] --> BUILD[svelte-kit build<br/>via Vite]
  BUILD --> ADAPT[adapter adapt&#40;&#41;<br/>sorts outputs]
  ADAPT --> ESB[esbuild<br/>SSR bundle, cjs]
  ADAPT --> STATIC[static files<br/>+ prerendered]
  ESB --> CDK[AWS CDK v2<br/>synth + deploy]
  STATIC --> CDK
  CDK --> STACK[CloudFormation stack<br/>Lambda, S3, CloudFront]

Building against a moving API#

The most uncomfortable part of the project has nothing to do with AWS. SvelteKit is in beta, and the adapter interface is among the parts that move most often. Methods on the builder object were renamed, merged and changed in behavior; the structure of the server output has also shifted more than once. An adapter built against SvelteKit from October may still compile in December – and still produce a broken deployment.

For an open source project, this means: the issues do not come from your own bugs but from the drift between the user’s framework version and the version the adapter was developed against. A typical bug report starts with “doesn’t work for me” and, after some digging, ends at a SvelteKit version that is three weeks newer than my last update. Only unspectacular measures help against this: pin the tested SvelteKit version in the project, keep example repositories up to date, follow changes to the framework promptly. That is the real price of building against a beta – and I consider it reasonable. If you wait until an interface is stable, you leave the experience from the meantime to others. Along the way, an adapter forces you to really understand the framework: you do not work with the documented surface but with the build output and its assumptions.

What the adapter concretely takes care of during the build is manageable and, precisely for that reason, easy to maintain:

  • sort client bundles, assets and prerendered pages into an artifact directory
  • bundle the server part with esbuild into a Lambda-ready file
  • place the handler shim for API Gateway next to it
  • synthesize a CDK stack and, if desired, roll it out directly
  • wire up domain, certificate and DNS records via Route 53 and ACM when an FQDN is set

What serverless does not take off your hands#

On the other side of the boundary, the second disillusionment is waiting: even with a finished adapter, AWS is not a platform that takes operations off your hands. Serverless moves work; it does not eliminate it. A few points became clear to me while running my own SvelteKit deployments.

Cold starts are real but manageable. An SSR function bundled with esbuild starts fast enough for most pages at this scale – but if you pull heavy dependencies into the server part, you pay for it with every cold request. With Lambda, the memory size is also the CPU dial: the 128 MB default is often too tight for rendering, and more memory can improve response times so much that it pays off despite the higher price per millisecond. Measure instead of guessing.

Then there is caching. CloudFront only relieves the function if the cache keys and headers are right – an SSR response with Cache-Control set to private hits the Lambda on every call. For small rewrites right at the edge, there have been CloudFront Functions since last year, which are much more lightweight than Lambda@Edge; for the actual rendering, both are the wrong place. And CloudFormation makes deployments traceable and reversible, but not fast: a change to the CloudFront distribution can take quite a few minutes. If you come from Vercel, you first have to get used to this pace.

What remains is an honest division of labor. The adapter answers the question “how does the app get to AWS” – these questions stay with the team:

  • Observability: which logs, metrics and alarms show that rendering is suffering?
  • Costs: what do requests, data transfer and logs cost under real traffic?
  • Security: which permissions does the SSR function have, and which does it really need?
  • Lifecycle: who keeps up with framework and adapter updates, and how is a rollback rehearsed?

Bottom line#

The project showed me two things that reach beyond SvelteKit and AWS. First: the adapter interface is a successful example of how a framework can draw a boundary without committing to a platform. Everything platform-specific – from the directory structure to the architecture decision – gets a clear place, and this place is versionable, testable and replaceable. The fact that a single person can provide a complete AWS foundation for a framework in a manageable repository speaks for the way this interface is cut.

Second: a deployment target is never just configuration. The path from svelte-kit build to a running CloudFront endpoint consists of nothing but small decisions – bundling, routing rules, cache behavior, memory sizes, log retention – and each of them has consequences in operations. A handwritten deploy script makes the same decisions, only invisibly and unversioned. An adapter makes them explicit and shares them with everyone who has the same problem. That is exactly why it is worth building something like this as open source, even when the framework is still in beta and the interface wobbles under your hands: the alternative is not “no adapter” but a hundred private scripts that all make the same mistakes again.

Further reading#

Revised and translated from German with the help of AI.