

# SvelteKit

**Welcome to the new AWS Amplify**  
Amplify now puts hosting, a Postgres database, and sign-in in one AWS account. Deploy from your terminal or from Git, check every change in a preview first, and roll back in one step if something breaks.  
Looking for Amplify Hosting? See the [Amplify Hosting User Guide](https://docs.aws.amazon.com/amplify/hosting/userguide/welcome.html).

SvelteKit is a framework for building web applications with Svelte. Amplify supports SvelteKit through a dedicated adapter that integrates backend capabilities into your SvelteKit apps.

## Why SvelteKit \+ Amplify?
<a name="_why_sveltekit_amplify"></a>
+  **Reactivity**: Svelte’s approach to reactivity eliminates the virtual DOM overhead.
+  **Performance**: SvelteKit’s build output works with Amplify’s edge deployment.
+  **Developer experience**: Svelte provides a concise syntax, and SvelteKit provides filesystem-based routing.
+  **Progressive enhancement**: SvelteKit’s form actions and page options support both JavaScript and no-JavaScript experiences.

## Prerequisites
<a name="_prerequisites"></a>
+ Node.js 22 or later
+ npm 10 or later
+ AWS credentials. For how to set them up, see [Configuring settings for the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html). A Git repository is optional.

## Getting started
<a name="_getting_started"></a>

Start by creating a new SvelteKit app:

```bash
# Create a new SvelteKit app
npx sv create my-sveltekit-app
cd my-sveltekit-app
```

Follow the prompts to set up your SvelteKit app with your preferred configuration options.

Next, add Amplify to your existing SvelteKit app:

```bash
# Add Amplify to your SvelteKit app
aws amplifygen3 create
```

The `create` command detects that you’re using SvelteKit and generates an `amplify.jsonc` file for your app. It then offers to install the SvelteKit adapter, which the build requires. If you decline, or your shell can’t answer the prompt (as in an agent session or CI), `create` prints the steps instead. To accept without a prompt, add `--yes`.

To finish the adapter setup, do the following. If `create` already installed the adapter package, skip the install step.

1. Install the adapter as a development dependency:

   ```bash
   npm install -D @aws-amplifygen3/adapter-sveltekit
   ```

1. In `vite.config.ts`, import the adapter and pass it to the `sveltekit()` plugin. SvelteKit 3, which `npx sv create` sets up, has no `svelte.config.js`. This needs version 0.1.9 or later of the adapter.

   ```ts
   import { sveltekit } from "@sveltejs/kit/vite"
   import adapter from "@aws-amplifygen3/adapter-sveltekit"
   import { defineConfig } from "vite"
   
   export default defineConfig({
     plugins: [sveltekit({ adapter: adapter() })],
   })
   ```

   On SvelteKit 2, set the adapter as `kit.adapter` in `svelte.config.js` instead.

## Configuring Amplify for SvelteKit
<a name="_configuring_amplify_for_sveltekit"></a>

The generated `amplify.jsonc` file builds your app and writes the output to the `.amplify` directory:

```jsonc
{
  "name": "my-sveltekit-app",
  "deploy": {
    "install": "npm ci",
    "build": "npm run build",
    "output_directory": ".amplify",
  },
}
```

## Use a backend with SvelteKit
<a name="sveltekit-support-backend"></a>

If your app has an Amplify backend, your SvelteKit code calls it with the client SDK, `@aws-amplifygen3/backend-client-js`, which needs Node.js 22.12 or later. Amplify creates and runs the backend. You own and manage any database that you connect yourself. For those, see [Use integrations in SvelteKit](#sveltekit-support-integrations) and [Working with a third-party database](#sveltekit-support-database). To add a backend and install the SDK, see [Amplify backend](deploy-backend.md) and the [client SDK README](https://github.com/aws-amplifygen3/amplifygen3/blob/main/packages/client-sdk/js/README.md) on GitHub.

Each deployment and `aws amplifygen3 local run` set `AMPLIFY_BACKEND_URL` and `AMPLIFY_BACKEND_PUBLISHABLE_KEY` for your build and your dev server. SvelteKit builds with Vite, so add a `define` next to `plugins` in `vite.config.ts` that inlines both values into browser code:

```ts
// vite.config.ts
import { defineConfig } from 'vite'

export default defineConfig({
  // Keep your existing plugins entry.
  define: {
    'import.meta.env.AMPLIFY_BACKEND_URL': JSON.stringify(process.env.AMPLIFY_BACKEND_URL ?? ''),
    'import.meta.env.AMPLIFY_BACKEND_PUBLISHABLE_KEY': JSON.stringify(process.env.AMPLIFY_BACKEND_PUBLISHABLE_KEY ?? ''),
  },
})
```

Leave `server.port` out of `vite.config.ts`. A port that the config pins is used even when another program holds it, which stops the dev server.

Create one client on first use:

```ts
import { createClient } from '@aws-amplifygen3/backend-client-js'

let client: ReturnType<typeof createClient> | undefined

export function backend() {
  if (!client) {
    client = createClient(import.meta.env.AMPLIFY_BACKEND_URL, import.meta.env.AMPLIFY_BACKEND_PUBLISHABLE_KEY)
  }
  return client
}
```

Call `backend()` only from browser code, such as `onMount` or an event handler. A page that SvelteKit renders on the server has no browser session, so don’t call it while the page renders. In `+page.server.ts` or `+server.ts`, `createClientFromEnv()` reads both variables from `process.env`. To read the signed-in user in server code, see [Server-side rendering](backend-auth-server-side.md).

To develop locally, run `aws amplifygen3 local run`. It starts the local backend and runs `vite dev` on the first free port from 5173, with `--strictPort`, and the local backend trusts that origin. A dev server that you start with `npm run dev` gets neither variable, and the local backend doesn’t trust it.

## Use integrations in SvelteKit
<a name="sveltekit-support-integrations"></a>

Amplify gives your app each integration’s connection details as environment variables, such as `BUCKET_NAME` for Amazon S3, `PGHOST` for Amazon Aurora DSQL, and `BEDROCK_MODEL_ID` for Amazon Bedrock. Each integration page lists its variables.

Read them with `process.env` in server-only code: `+server.ts` endpoints, `+page.server.ts` load functions, and `hooks.server.ts`. Integration variables aren’t available in client code. To use a value in the browser, return it from a server load function. The page gets it in `data`.

The following endpoint queries Amazon Aurora DSQL on the server. Install the packages first:

```bash
npm install @aws/aurora-dsql-node-postgres-connector drizzle-orm pg
```

```ts
// src/routes/api/users/+server.ts
import { json } from "@sveltejs/kit"
import type { RequestHandler } from "./$types"
import { AuroraDSQLPool } from "@aws/aurora-dsql-node-postgres-connector"
import { drizzle } from "drizzle-orm/node-postgres"
import { sql } from "drizzle-orm"

const pool = new AuroraDSQLPool({
  host: process.env.PGHOST,
  user: process.env.PGUSER,
})

const db = drizzle({ client: pool })

export const GET: RequestHandler = async ({ url }) => {
  const id = url.searchParams.get("id")
  const { rows } = await db.execute(sql`SELECT * FROM users WHERE id = ${id}`)
  return json(rows)
}
```

This code works for the following reasons:
+ The integration sets `PGHOST` and `PGUSER`. The Aurora DSQL connector reads them. Aurora DSQL has no password. The connector generates a short-lived IAM authentication token for each connection, and it refreshes the token for you.
+  `sql` is a template tag from Drizzle. Drizzle turns the template into a query with parameters. A value in `${…​}`, such as `id`, goes to the database as a parameter and not as part of the SQL text, so the value can’t change the query.
+  `db.execute` sends the query through the connection pool and returns the rows.

If the browser must read a value, create a `custom` integration and give the variable a `PUBLIC_` prefix. For code that uses each service, see [Working with a third-party database](#sveltekit-support-database), [Amazon Aurora DSQL](integrations-amazon-aurora-dsql.md), [Amazon S3](integrations-amazon-s3.md), and [Amazon Bedrock](integrations-amazon-bedrock.md).

## Working with a third-party database
<a name="sveltekit-support-database"></a>

This section is for a database that Amplify doesn’t create, such as a Postgres database from a third-party provider, or a database in your VPC. For an Amazon Aurora DSQL cluster, see the example in [Use integrations in SvelteKit](#sveltekit-support-integrations). If you use an Amplify backend, use the backend client library instead. See [Use a backend with SvelteKit](#sveltekit-support-backend).

Connect the database to your app as a `custom` integration. Define the connection variables that the `postgres` library reads: `PGHOST`, `PGPORT`, `PGDATABASE`, `PGUSER`, and `PGPASSWORD`. Amplify reads the secret `PGPASSWORD` from a dotenv file, so the password doesn’t appear on the command line. Replace the values with your own, and connect the integration to the `preview` environment:

```bash
aws amplifygen3 integration connect custom --name my-database \
  --integ-env-var PGHOST=db.example.com \
  --integ-env-var PGPORT=5432 \
  --integ-env-var PGDATABASE=app \
  --integ-env-var PGUSER=app_user \
  --integ-secret-env-var PGPASSWORD --integ-secret-env-file .env.secrets \
  --env preview
```

A `custom` integration connects only to an environment whose role permissions mode is `full`.

You can use the same approach to connect to a database in your VPC. First connect your app to the VPC, as described in [Connect your app to private resources](customize-your-app-vpc.md). Then set `PGHOST` to the private address of the database.

Then connect the integration to your other environments:

```bash
aws amplifygen3 integration connect --name my-database --env production
```

Read and write the database in `+page.server.ts`. The `postgres` library reads the `PG*` variables from `process.env`, so `postgres()` needs no arguments. The `sql` tag sends each `${…​}` value to the database as a parameter, not as part of the SQL text:

```ts
// src/routes/notes/+page.server.ts
import { fail } from "@sveltejs/kit"
import type { Actions, PageServerLoad } from "./$types"
import postgres from "postgres"

const sql = postgres()

export const load: PageServerLoad = async () => {
  const notes = await sql`select * from notes order by created_at desc`
  return { notes }
}

export const actions: Actions = {
  default: async ({ request }) => {
    const content = (await request.formData()).get("content")

    if (!content || typeof content !== "string") {
      return fail(400, { error: "Content is required" })
    }

    await sql`insert into notes (content) values (${content})`
    return { success: true }
  },
}
```

The page receives `notes` in `data`. A form on the page that posts to the default action adds a note. SvelteKit runs the load function again after the action, so the page shows the new note.

## Deploying your SvelteKit \+ Amplify app
<a name="_deploying_your_sveltekit_amplify_app"></a>

Deploy your app with a single command:

```bash
aws amplifygen3 deploy
```

Amplify builds and deploys your SvelteKit application to the edge. After deployment, you receive a unique URL for your site.

## Local development
<a name="_local_development"></a>

The Amplify adapter runs only when Amplify builds your app, so the SvelteKit development server doesn’t get your environment’s variables. To use them locally, download them to `.env.local`. The file includes your integrations' variables, and it writes secrets with empty values, so fill those in yourself:

```bash
aws amplifygen3 var download .env.local --env preview
```

Then start the development server with hot reloading:

```bash
# Start development server
npm run dev
```

For an app with a backend, run `aws amplifygen3 local run` instead, which starts the local backend and your dev server with the backend’s URL and publishable key.