Skip to content

Adapter Design: Where Frameworks End

What a framework adapter really does: the contract over the build output, the translation of request and response, and the silent environment assumptions at the boundary between SvelteKit and AWS.

≈ 10 min readSoftwareAWSCloud

Adapter Design: Where Frameworks End

An adapter in the SvelteKit sense is neither a textbook design pattern nor a deployment tool. It is a piece of code that runs after the build, takes the framework’s output and turns it into something a concrete platform can execute: a Node server, a Lambda function, a worker at the network edge. It starts no processes, it serves no requests, and at its core it provisions no infrastructure. It translates.

The definition sounds harmless. What is interesting is what it implies: an adapter is exactly the place where a framework stops taking responsibility – and the platform begins. Everything before this place belongs to the framework: routing, rendering, data loading, the semantics of a page. Everything after it belongs to the platform: process model, network, file system, limits, price tag. If you write an adapter, you do not draw this boundary yourself, but you have to trace it precisely. And in doing so, you notice how many decisions were made silently on both sides.

Since the beginning of the year, I have been maintaining such an adapter: sveltekit-adapter-aws brings SvelteKit applications to Lambda, S3 and CloudFront via CDK. I have already introduced the project itself – this post is about what I learned about the interface while building it. Because the real insight is not in the AWS part but in the question every adapter has to answer: what belongs on which side?

The contract over the build output#

SvelteKit gives an adapter surprisingly little – and that is exactly what is good about it. The interface consists of an object with a name and an adapt function that receives a builder object. The builder is the complete contract: it provides the client assets, the prerendered pages and the server code, plus a manifest with the route metadata. Nothing more.

import { writeFileSync } from 'node:fs';

export function adapter(options = {}) {
  return {
    name: 'sveltekit-adapter-aws',
    async adapt(builder) {
      const out = 'build';
      builder.rimraf(out);

      builder.writeClient(`${out}/assets`);        // static files for the CDN
      builder.writePrerendered(`${out}/prerendered`);
      builder.writeServer(`${out}/server`);        // the SSR part

      const manifest = builder.generateManifest({ relativePath: './' });
      writeFileSync(
        `${out}/server/manifest.js`,
        `export const manifest = ${manifest};`
      );
    }
  };
}

With this, the framework says: there are three kinds of artifacts, and I write them wherever you want them. Where they ultimately belong, how they are delivered, what a “server” even is on your platform – your problem. For AWS, this concretely means: client assets and prerendered pages go into an S3 bucket behind CloudFront, the server code is built into a Lambda bundle with esbuild, and the routing rules of the CDN distribution have to decide which request goes to S3 and which to the function.

flowchart LR
  subgraph FW[Framework-Seite]
    SRC[Quellcode] --> VITE[Vite-Build]
    VITE --> CL[Client-Assets]
    VITE --> PR[Prerenderte<br/>Seiten]
    VITE --> SV[Server-Code +<br/>Manifest]
  end
  subgraph AD[Adapter]
    CL --> MAP[Zuordnung,<br/>Bundling]
    PR --> MAP
    SV --> MAP
  end
  subgraph PF[Plattform-Seite]
    MAP --> S3[S3-Bucket]
    MAP --> LB[Lambda-Bundle]
    S3 --> CF[CloudFront]
    LB --> CF
  end

The mapping in the middle box is the part nobody sees and where most of the work lies. Which paths are static, which are dynamic? What happens to a prerendered page that also has a server route? Who sets the cache headers? The framework has an opinion on this, but it does not enforce it – it cannot enforce it, because it does not know the platform. The adapter has to translate the framework’s opinion into the platform’s mechanics without inventing a third opinion of its own.

Request and response as a common language#

At runtime, the contract is even narrower. The SvelteKit server speaks the web standards: it takes a Request object from the Fetch API and returns a Response object. That is a deliberate and, in my view, smart decision – the same types that have existed in the browser for years and that Deno Deploy and Cloudflare Workers use as their native format anyway. The newly founded WinterCG is currently trying to standardize exactly this core of server-side web APIs across runtimes. SvelteKit committed to it even before that.

For the adapter, this means: its runtime job is one translation there and one back. AWS does not speak Fetch; AWS speaks API Gateway events. The handler in my Lambda bundle therefore essentially does only this:

import { Server } from './index.js';
import { manifest } from './manifest.js';

const server = new Server(manifest);
await server.init({ env: process.env });

export async function handler(event) {
  const request = toRequest(event); // API Gateway event -> fetch Request
  const response = await server.respond(request, {
    getClientAddress: () => event.requestContext.http.sourceIp
  });
  return toLambdaResult(response); // fetch Response -> Lambda result
}

The two inconspicuous functions toRequest and toLambdaResult are where the platform shows its quirks. An API Gateway event carries query parameters already split up; the Request wants a complete URL. Binary responses have to be Base64-encoded, and whether something is “binary” is decided by the adapter based on the content type – a heuristic you get wrong for the first time at some point. And Set-Cookie is the classic: several cookies in one response are merged into one line by the Headers implementation, while API Gateway expects them as a separate array.

async function toLambdaResult(response) {
  const contentType = response.headers.get('content-type') || '';
  const isBinary = !/^(text\/|application\/(json|javascript))/.test(contentType);

  return {
    statusCode: response.status,
    headers: Object.fromEntries(response.headers.entries()),
    // API Gateway expects cookies as a separate array
    cookies: splitSetCookie(response.headers.get('set-cookie')),
    body: isBinary
      ? Buffer.from(await response.arrayBuffer()).toString('base64')
      : await response.text(),
    isBase64Encoded: isBinary
  };
}

None of this is difficult. But all of it is responsibility that the framework explicitly does not take on – and should not take on either. If SvelteKit started knowing API Gateway quirks, tomorrow it would also have to know those of Azure, Google and every host that invents its own event structure. The narrow Fetch API is the boundary that keeps both sides independent.

sequenceDiagram
  participant C as Client
  participant CF as CloudFront
  participant L as Lambda-Handler
  participant K as SvelteKit-Server
  C->>CF: HTTP-Request
  CF->>L: API-Gateway-Event
  L->>K: fetch Request
  K-->>L: fetch Response
  L-->>CF: statusCode, headers,<br/>cookies, body
  CF-->>C: HTTP-Response

The silent assumptions of the environment#

The third part of the boundary is the most unpleasant because it appears in no interface signature: the assumptions about the environment. A SvelteKit application may run almost arbitrary Node code in its server routes. Which of it works on the target platform only the adapter knows – and often only operations.

On Lambda, I kept running into three points:

  • The file system is read-only, except for /tmp. If your server code stores files, writes caches to disk or expects an SQLite file next to the code, it falls flat on its face with the first real request – locally with vite dev, everything works.
  • Environment variables come from the function configuration, not from a .env file. SvelteKit now has the hook server.init({ env }) for this, through which the adapter passes the variables in explicitly. It is exactly such small handover points that make the boundary honest: the environment is a parameter, not global state.
  • There is no streaming. Lambda behind API Gateway buffers the complete response and delivers it in one piece, with hard size limits. A Response with a slow stream as its body simply cannot be represented on this platform – the adapter has to collect the stream and materialize it.

The last point shows why adapter design is more than format conversion. With the Response type, the framework promises a capability – streaming bodies – that the platform cannot deliver. The adapter cannot fix that; it can only make it visible: document it, warn during the build if in doubt, and buffer the response correctly instead of cutting it off. Where framework promises and platform capabilities diverge, the adapter is the one that has to explain the difference.

When the framework side moves#

In October 2022, SvelteKit is still pre-1.0, and as an adapter author you notice that more clearly than as an application developer. Since the beginning of the year, I have had to touch the adapter integration several times: app.render(request) became server.respond(request, options), the manifest format and the builder methods shifted, and the big routing overhaul in late summer changed what ends up in the server output at all. The switch to Vite 3 added the tooling level on top.

I do not want this to be understood as a complaint – a framework before 1.0 may change its interfaces; that is what this phase is for. Something else was revealing: each of these changes showed me which of my assumptions belonged to the contract and which I had only imagined. If you have to catch up with an interface three times, you understand it better afterward than someone who has read it once.

In practice, I drew two consequences from this. First: the SvelteKit version is pinned exactly in the adapter project, and every update is a deliberate step with its own commit instead of an incidental npm update. Second: the most important test is not a unit test of the conversion functions but an example project that is actually built and deployed with every change. An adapter is a consumer of an unstable API; the only reliable check is the one that goes the whole way – from vite build to the HTTP response from CloudFront. Everything else only tests your own idea of the contract, not the contract.

The same boundary, other frameworks#

The question “what belongs on which side” comes up everywhere; the frameworks just answer it differently – and the answers are revealing.

Next.js has no adapter interface. The platform is implicitly Vercel, and if you deploy elsewhere, you struggle with an output that was never meant for it. What I find remarkable is that Vercel turned the tables this year with the Build Output API: there, the platform defines a documented directory format, and any framework can build toward it. That is the same boundary, just drawn from the other side – instead of “the framework defines, the adapter translates,” it is “the platform defines, the framework delivers.” Whoever owns the contract holds power over the boundary.

Remix, in turn, built in the translation from the start: createRequestHandler takes platform-specific requests, and official adapters exist for Express, Architect and Cloudflare Workers. There, too, the core is identical to what SvelteKit does – web standard Request in, web standard Response out, and around it a thin layer of platform dialect. The more consistently frameworks commit to these standards, the thinner the adapters become. In the best case, the runtime translation shrinks to zero, as with Deno Deploy and the Workers, which speak Fetch natively, and only the build output part remains.

What I take away from this#

An adapter is the most honest place in a framework architecture because nothing can be abstracted away there. On one side stands what the framework really guarantees: three kinds of artifacts, a manifest, a Fetch API. On the other side stands what the platform really demands: its event format, its file system, its limits. The adapter in between should be boring and thin. If it gets thick, that is a finding – then either the framework guarantees too little or the platform demands too much, and you should know both before you build an application on it.

That is why looking into the adapter is worthwhile even for those who will never write one. If you understand what adapter-node or an AWS adapter does in detail, you know exactly which assumptions your own application makes about its environment – and which of them will break at the next platform change. The boundary between framework and platform does not disappear because you ignore it. It just becomes invisible. A good adapter makes it visible again, and that is worth more than any other feature it brings along.

Further reading#

Revised and translated from German with the help of AI.