Svelte with Thin

Learn how to add Thin Backend to your Svelte application

1. Introduction

This guide covers how to use Thin as the Backend for your Svelte application.

If you haven't already, start by generating a new Svelte project:

npx degit sveltejs/template my-svelte-project
cd my-svelte-project

# Enable TypeScript (recommended)
node scripts/setupTypeScript.js

npm install

Now you can start the Svelte development server:

npm run dev

2. Install Packages

Install the Thin Backend package:

npm install thin-backend

3. Init

Now that we have installed the Thin Backend packages, we need to call initThinBackend from the entrypoint of the Svelte app to initalize Thin Backend.

Open the project's main.ts and add a call to initThinBackend like this:

import App from './App.svelte';

// Add this import
import { initThinBackend } from 'thin-backend';

// Then call `initThinBackend`
initThinBackend({
    // This url is different for each backend, you can find the backend url in the project documentation
    host: 'https://<YOUR PROJECTS BACKEND_URL>'
});

const app = new App({
    target: document.body,
    props: {
    }
});

Now your react application is connected to your Thin Backend and you can now use Thin Backend for accessing your database and managing auth.

4. Installing Types (Optional)

Thin Backend generates TypeScript Type Definitions based on your database schema. This catches most runtime errors ahead of time, while providing really nice autocompletion in VSCode and other editors.

The custom Types can be installed into a project by installing a custom npm package. This npm package is specifically generated for your project and tagged with a secret url, so only you can access it.

To install your project's Types, open the Schema Designer. Click the Type Definitions tab. Now you see a npm install .. command:

Run this command locally in your project directory. After that the types will be automatically available in your project.

When you make changes to the database schema, a new type definition package will be generated. To use the latest types, open the Type Definitions tab again and install the latest package listed there.

5. Login

Next we need to make sure that our user is logged in before the app can be used. For that we're going to call ensureIsUser The ensureIsUser makes sure that the react app is only shown when the user is logged in in Thin Backend's Auth Service. If the user is not logged in yet, it will redirect to the login page.

Open App.svelte and change it to this:

<script lang="ts">
    import { ensureIsUser } from 'thin-backend';
    import { onMount } from 'svelte';
    
    export let loginCompleted = false;

    onMount(async () => {
        await ensureIsUser();
        loginCompleted = true;
    });
</script>

<main>
    <h1>App</h1>
    {#if loginCompleted}
        <div>Logged in</div>
    {/if}
</main>

This will set the loginCompleted to true once the user is logged in.

6. Fetching Data

You can use the query function to access your project's database. Let's say your building a todo list app and you've previously created a tasks table in the Schema Designer. The following code will show all tasks and a button to add new tasks.

Create a file Tasks.svelte with this content:

<script lang="ts">
    import { createRecord, query, getCurrentUserId } from 'thin-backend';
    
    const tasks = query('tasks').orderBy('createdAt');

    function addTask() {
        createRecord('tasks', {
            title: window.prompt('Enter title:') || '',
            userId: getCurrentUserId()
        })
    }
</script>

<main>
    {#if $tasks}
        {#each $tasks as todo}
            <div>{todo.title}</div>
        {/each}
    {:else}
        <div>Loading tasks</div>
    {/if}

    <button on:click={addTask}>Add Task</button>
</main>

The query('tasks').orderBy('createdAt') call, used via Svelte's autosubscribe as $tasks sets up a subscription behind the scences. Whenever the result set of our query('todos').orderBy('createdAt') we fired here changes, it will trigger a re-render of our component.

The createRecord('tasks', { .. }) call insert something into the tasks table.

We also need to call the new Tasks.svelte from our App.svelte. Change the App.svelte to this:

<script lang="ts">
    // ...

    // Import the new component
    import  Tasks from './Tasks.svelte';

    // ...
</script>

<main>
    <h1>App</h1>
    {#if loginCompleted}

        // Display the tasks once logged in:
        <Tasks />
    
    {/if}
</main>

Check out the Database Guide for a full list of all database operations you can do with Thin.

Next: Database Guide

Community

If you need any help or input, feel free to ask in the Thin Community Forum.