SvelteKit: The Adapter Architecture
2020 has been a big year for Svelte. With the announcement of SvelteKit (the successor to Sapper), the community is shifting towards a "write once, deploy anywhere" mentality. The secret sauce is the Adapter Architecture.
What is an Adapter?
In SvelteKit, the build process is split into two phases:
- Analysis and Compilation: SvelteKit compiles your app into a platform-agnostic intermediate format.
- Adaptation: An adapter takes that format and transforms it into the specific code needed for your target environment (Vercel, Netlify, Cloudflare Workers, or a Node.js server).
How it works
When you run svelte-kit build, the framework generates a manifest and a set of server-side chunks. The adapter then wraps these in a handler.
For example, a simplified Node.js adapter looks like this:
// adapter-node/index.js
import { render } from './server/index.js';
export default function(options) {
return {
name: 'adapter-node',
async adapt(builder) {
builder.copy_server_files('build');
builder.copy_static_files('build/static');
// Generate the entry point
builder.write_server(`
import { createServer } from 'http';
import { handler } from './handler.js';
const { PORT = 3000 } = process.env;
createServer(handler).listen(PORT);
`);
}
};
}
Edge Computing and Serverless
The beauty of this system is its efficiency on the Edge. Because SvelteKit is designed to be lightweight, adapters for Cloudflare Workers can produce bundles that stay within the 1MB limit while still providing full SSR (Server Side Rendering) and routing.
// src/routes/api/data.js
export async function get({ params }) {
const data = await fetchFromDB();
return {
body: data
};
}
By abstracting the deployment target away from the application logic, SvelteKit allows developers to focus on building their apps without worrying about the underlying infrastructure until the very last step.
Aunimeda develops websites and web applications for businesses - corporate sites, e-commerce, portals, and custom platforms.
Contact us to discuss your web project. See also: Web Development, E-commerce Development