Article SvelteKit Xata Serverless

Up and running with SvelteKit and Xata

Integrate Xata in SvelteKit

Xata is a very new, just out of a private beta serverless database. Let's see how well it works together with SvelteKit :)

Basic starter

We start by creating our basic SvelteKit project

npm create svelte@latest sveltekit-xata
cd sveltekit-xata
npm install
git init
git add .
git commit -m"init"

Let's verify that everything is working by running npm run dev Open the browser and verify that the page is working.

Xata

Next, we install xata to make use of their CLI tool. Could also just use npx.

npm i -g @xata.io/CLI

Next, we need to make an authentication so we run xata auth login. We are prompted to add an API key. If you have not done this before just use create a new existing API key by opening a browser :)

Now that we are authenticated we can initialize the app.

xata init

Just follow the questions. After running init our.env file should have been automatically updated for you to include XATA_API_KEY and XATA_FALLBACK_BRANCH with their values. You can generate a new API key via settings

Schemas

Go to https://app.xata.io/ and update your database by e.g. adding a new table. Then run xata codegen to generate new schemas. You can also make use of xata schema edit to get an interactive console to edit our schema.

After running codegen a new file should have been created named src/xata.ts (The path for this file is defined in .xatarc)

...
"codegen": {
  "output": "src/xata.ts"
}

This file contains all schema information and type definitions.

Now we can fetch some data! Just remember to fill your new table with some data :)

Data fetching

We keep it simple and just create a page.server.ts file to query some data.

import { XataClient } from '../lib/xata';
import { env } from '$env/dynamic/private';

const xata = new XataClient({ apiKey: env.XATA_API_KEY });

/** @type {import('./$types').PageServerLoad} */
export async function load({ params }) {
    const users = await xata.db.users.getMany();
    return {
        users: users
    };
}

That's it we now are passing our users to the client side! 💯

Will be interesting to compare Xata to Supabase and see what the difference is. Maybe a side-by-side comparison creating a basic app using both databases. Would that be interesting? 🤔