Writing a CRUD App With Svelte and Pocketbase

Writing a CRUD App With Svelte and Pocketbase

This tutorial will guide you through building a simple Svelte application that performs CRUD (Create, Read, Update, Delete) operations using the PocketBase API.

PocketBase is an open-source backend solution that provides a lightweight, self-hosted backend service with a built-in database, authentication, and file storage.

Integrating Svelte with PocketBase allows you to create a fully functional front-end application with a minimal backend setup.

Step 1: Set Up PocketBase

Download and Run PocketBase:PocketBase will start and be accessible at http://localhost:8090.

    • Download the latest PocketBase release from the official PocketBase website.
    • Unzip the file and navigate to the extracted directory in your terminal.

Create a Collection:

    • Open your browser and navigate to http://localhost:8090/_.
    • Create a new collection called tasks with the following fields:
      • title (type: text)
      • description (type: text)
    • Save the collection and note the API endpoint.

Run PocketBase using the following command:

./pocketbase serve

Step 2: Set Up Svelte

Create a New Svelte Project:

npx degit sveltejs/template svelte-pocketbase-crud
cd svelte-pocketbase-crud
npm install
  1. Install Axios:
npm install axios

We'll use Axios to interact with the PocketBase API:

Step 3: Set Up API Interaction

  1. Create an API Service:

Create a new file src/lib/api.js to handle API requests:

import axios from 'axios';

const api = axios.create({
    baseURL: 'http://localhost:8090/api/collections/tasks/records',
});

export const getTasks = () => api.get('/');
export const createTask = (data) => api.post('/', data);
export const updateTask = (id, data) => api.patch(`/${id}`, data);
export const deleteTask = (id) => api.delete(`/${id}`);

Step 4: Create the Svelte Components

Display Task List:

Create a new Svelte component src/routes/index.svelte:

    import { onMount } from 'svelte';
    import { getTasks, createTask, updateTask, deleteTask } from '../lib/api';

    let tasks = [];
    let title = '';
    let description = '';
    let editMode = false;
    let currentTask = null;

    onMount(async () => {
        const response = await getTasks();
        tasks = response.data.items;
    });

    const addTask = async () => {
        const newTask = { title, description };
        const response = await createTask(newTask);
        tasks = [...tasks, response.data];
        title = '';
        description = '';
    };

    const startEdit = (task) => {
        title = task.title;
        description = task.description;
        currentTask = task;
        editMode = true;
    };

    const saveTask = async () => {
        const updatedTask = { title, description };
        const response = await updateTask(currentTask.id, updatedTask);
        tasks = tasks.map(task => task.id === currentTask.id ? response.data : task);
        title = '';
        description = '';
        editMode = false;
    };

    const removeTask = async (id) => {
        await deleteTask(id);
        tasks = tasks.filter(task => task.id !== id);
    };
</script>

<main>
    <h1>Task Manager</h1>

    <input type="text" bind:value={title} placeholder="Title" />
    <textarea bind:value={description} placeholder="Description"></textarea>

    {#if editMode}
        <button on:click={saveTask}>Save Task</button>
    {:else}
        <button on:click={addTask}>Add Task</button>
    {/if}

    <ul>
        {#each tasks as task}
            <li>
                <h2>{task.title}</h2>
                <p>{task.description}</p>
                <button on:click={() => startEdit(task)}>Edit</button>
                <button on:click={() => removeTask(task.id)}>Delete</button>
            </li>
        {/each}
    </ul>
</main>

Step 5: Run the Svelte Application

Start the Development Server:

npm run dev

Access the Application:

Open your browser and navigate to http://localhost:5000 to interact with the CRUD application.

Run the Svelte development server:

Deploy to Vercel

Steps to Deploy the Svelte PocketBase CRUD App to Vercel

After building your Svelte app with PocketBase integration, you can deploy it to Vercel, a popular platform for hosting front-end applications. Below are the steps to deploy your Svelte app to Vercel.

Step 1: Prepare Your Svelte App for Deployment

Build the Svelte App:This command will generate a public directory containing the compiled Svelte files.

Before deploying, build your Svelte app to optimize it for production:

npm run build

Step 2: Create a Vercel Account

Sign Up for Vercel:

If you don’t have a Vercel account, sign up at vercel.com.

Install Vercel CLI (Optional):

npm install -g vercel

You can use the Vercel CLI to deploy your project from the command line:

Step 3: Deploy to Vercel

Connect Your Git Repository:

  1. If your Svelte project is in a Git repository (e.g., GitHub, GitLab, Bitbucket), you can connect it directly to Vercel.
  2. Go to your Vercel dashboard and click "New Project."
  3. Select your Git provider and authorize Vercel to access your repositories.
  4. Choose the repository containing your Svelte project.

Configure the Project:

  1. In the Vercel dashboard, configure the project settings:
    • Framework Preset: Select "Svelte" as the framework.
    • Build Command: Ensure it's set to npm run build.
    • Output Directory: Set it to public.

Environment Variables:

If your application uses environment variables (e.g., for the PocketBase API URL), configure them in the Vercel dashboard:

    • Go to the "Environment Variables" section.
    • Add the variables used in your Svelte app (e.g., POCKETBASE_URL).
    • Ensure the API URL points to the live PocketBase instance.

Deploy the Project:

  1. Click "Deploy" to start the deployment process.
  2. Vercel will automatically build and deploy your Svelte app.

Step 4: Access Your Deployed App

View the Deployed App:

  1. After deployment, Vercel will provide a live URL where your app is hosted.
  2. Visit the URL to see your Svelte app in action.

Test CRUD Operations:

Verify that the CRUD operations work as expected by interacting with the app.

Step 5: Configure Custom Domain (Optional)

Add a Custom Domain:

  1. If you have a custom domain, you can add it to your Vercel project.
  2. Go to the "Domains" section in your project settings.
  3. Add your domain and follow the DNS configuration instructions.

HTTPS Configuration:

Vercel automatically provides an SSL certificate for your domain, ensuring that your site is served over HTTPS.

Step 6: Set Up Automatic Deployments (Optional)

Enable Automatic Deployments:

Vercel supports automatic deployments for every push to your Git repository.

Every time you push changes to your repository, Vercel will build and deploy the latest version of your app.

Step 7: Monitor and Manage Your App

Check Deployment Status:

In the Vercel dashboard, you can monitor the status of your deployments and view logs.

Manage Environment Variables:

Update environment variables as needed directly from the Vercel dashboard.

Conclusion

You now have a fully functional Svelte application that performs CRUD operations with a PocketBase backend. This setup allows you to manage tasks efficiently with a minimal codebase. By leveraging PocketBase's API and Svelte's reactive UI, you can quickly build and deploy scalable applications.

Deploying your Svelte PocketBase CRUD app to Vercel is a straightforward process that provides a robust, scalable hosting solution. By following these steps, your app will be live and accessible to users, with the added benefits of Vercel's continuous deployment and monitoring capabilities.








Open-source Apps

9,500+

Medical Apps

500+

Lists

450+

Dev. Resources

900+