Dev.to WebDev 🛠 Dev 👁 0 📖 8 min read

Build a Simple CRUD App with PocketBase and htmx (Beginner Guide)

In this guide, we build a small todo app. You can add a todo, mark it as done, and delete it. These actions are called CRUD: Create, Read, Update, Delete. We use three tools: PocketBase: a backend in one file. It has

Build a Simple CRUD App with PocketBase and htmx (Beginner Guide)

In this guide, we build a small todo app. You can add a todo, mark it as done, and delete it. These actions are called CRUD: Create, Read, Update, Delete.

We use three tools:

  • PocketBase: a backend in one file. It has a database (SQLite), user login and an admin dashboard. You can also add your own server code in JavaScript.
  • htmx: a small JavaScript library. You add special attributes to your HTML, like hx-post. htmx sends a request to the server. Then it puts the HTML from the server into the page.
  • pbc: the command-line tool (CLI) for PocketBase Cloud. We use it to create the project, create the database table, look at the data and deploy.

The main idea is simple: the server sends HTML, not JSON. So we don't need React, a build step or node_modules.

This is the app we will build:

The finished todo app: adding, checking and deleting todos

Do you prefer video? Watch the full walkthrough here:

Words you will see

Word Meaning
Collection A table in the PocketBase database. Our table is called todos.
Record One row in a collection. One todo is one record.
Hook JavaScript code that runs inside PocketBase, on the server. Hook files go in pb_hooks/.
Route A URL plus an HTTP method, for example POST /app/todos. When a request matches, our code runs.
HTTP method The type of request: GET reads, POST creates, PATCH updates, DELETE deletes.
Migration A file that describes a change to the database structure. PocketBase creates these for you.
Superuser The admin account of a PocketBase instance.

What you need

  • A terminal
  • A browser
  • A code editor

How the app works

How the app works: pbc creates the project, the browser talks to PocketBase with htmx, hooks save to the todos collection

  1. The browser opens the page pb_public/index.html.
  2. You click something. htmx sends a request to one of our routes.
  3. The route (in pb_hooks/) reads or changes the todos collection.
  4. The route sends back a small piece of HTML.
  5. htmx puts that HTML into the page.

All of this runs in one PocketBase program.

These are the files we will have at the end:

Project structure

Step 1: Create the project

First, install the pbc CLI:

curl -fsSL https://raw.githubusercontent.com/pocketbasecloud/cli/main/scripts/install.sh | sh

Then create a folder and set up PocketBase in it:

mkdir todos-htmx
cd todos-htmx
pbc local init
./pocketbase serve

pbc local init downloads PocketBase and creates the project

What happened:

  • pbc local init downloaded the PocketBase program for your computer.
  • It created two folders: pb_hooks/ for server code and pb_migrations/ for migrations.
  • It saved the PocketBase version in pbc.json. Now your team and the cloud use the same version. To choose a version yourself, run pbc local init 0.39.9.
  • It also created an example file, pb_hooks/main.pb.js. We don't need it. You can delete it.
  • ./pocketbase serve started the server at http://127.0.0.1:8090.

Keep this terminal open. The server must keep running.

Step 2: Create the todos collection

Open a second terminal in the same folder. Create a superuser, then log in with pbc:

./pocketbase superuser upsert [email protected] 'a-long-password'
pbc admin login --url http://127.0.0.1:8090

The second command asks for your email and password.

Now create a file named todos.json. It describes the collection:

{
  "name": "todos",
  "fields": [
    { "name": "title", "type": "text", "required": true },
    { "name": "completed", "type": "bool" },
    { "name": "created", "type": "autodate", "onCreate": true }
  ]
}

The collection has three fields:

  • title: the text of the todo. It is required.
  • completed: true or false.
  • created: a date and time. PocketBase fills it in when a record is created.

Create the collection with one command:

pbc admin collections create "$(cat todos.json)"

Creating the collection with pbc, and the new migration file

Look in the pb_migrations/ folder. There is a new file. PocketBase writes a migration every time the database structure changes. Later, when we deploy, this file creates the same collection on the server.

Step 3: Write routes that return HTML

The template

Create pb_hooks/views.js. It has the HTML for one todo:

const ITEM = `<li id="todo-{{.id}}">
  <input type="checkbox" {{if .completed}}checked{{end}}
    hx-patch="/app/todos/{{.id}}" hx-target="#todo-{{.id}}" hx-swap="outerHTML">
  <span>{{.title}}</span>
  <button hx-delete="/app/todos/{{.id}}" hx-target="#todo-{{.id}}" hx-swap="outerHTML">×</button>
</li>`

module.exports = {
  item: (r) => $template.loadString(ITEM).render({
    id: r.id,
    title: r.getString("title"),
    completed: r.getBool("completed"),
  }),
}

What this code does:

  • ITEM is an HTML template for one <li>. Values like {{.title}} are filled in later.
  • {{if .completed}}checked{{end}} adds checked to the checkbox when the todo is done.
  • The checkbox has hx-patch. When you click it, htmx sends a PATCH request.
  • The × button has hx-delete. When you click it, htmx sends a DELETE request.
  • hx-target="#todo-{{.id}}" and hx-swap="outerHTML" mean: "replace this whole <li> with the HTML from the server."
  • $template uses Go's html/template. It escapes HTML automatically. If a user types <script> into the input, it is shown as text. It does not run.

The four routes

Create pb_hooks/todos.pb.js:

routerAdd("GET", "/app/todos", (e) => {
  const views = require(`${__hooks}/views.js`)
  const todos = $app.findRecordsByFilter("todos", "", "created", 100, 0)
  return e.html(200, todos.map(views.item).join(""))
})

routerAdd("POST", "/app/todos", (e) => {
  const views = require(`${__hooks}/views.js`)
  const todo = new Record($app.findCollectionByNameOrId("todos"))
  todo.set("title", e.requestInfo().body.title)
  $app.save(todo)
  return e.html(200, views.item(todo))
})

routerAdd("PATCH", "/app/todos/{id}", (e) => {
  const views = require(`${__hooks}/views.js`)
  const todo = $app.findRecordById("todos", e.request.pathValue("id"))
  todo.set("completed", !todo.getBool("completed"))
  $app.save(todo)
  return e.html(200, views.item(todo))
})

routerAdd("DELETE", "/app/todos/{id}", (e) => {
  $app.delete($app.findRecordById("todos", e.request.pathValue("id")))
  return e.html(200, "")
})
Route What it does What it returns
GET /app/todos Gets all todos, oldest first All the <li> rows
POST /app/todos Creates a todo from the form The new <li>
PATCH /app/todos/{id} Switches completed between true and false The updated <li>
DELETE /app/todos/{id} Deletes the todo An empty string, so the row disappears

Important notes:

  • Put require inside each handler. PocketBase runs each handler in its own separate context. A handler can't see variables or functions from the top of the file. That's why we load views.js inside every handler. The PocketBase docs recommend this.
  • Our URLs start with /app/. PocketBase already uses /api/ for its own API. Files in pb_public/ are served from /. The /app/ prefix keeps our routes separate from both.
  • No restart needed. PocketBase reloads the hooks when you save a file.

Step 4: Write the page

Create pb_public/index.html. This is the whole frontend:

<!doctype html>
<meta charset="utf-8">
<title>Todos</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/light.css">
<script src="https://unpkg.com/[email protected]"></script>
<style>li:has(:checked) span { text-decoration: line-through; opacity: .5 }</style>

<h1>Todos</h1>
<form hx-post="/app/todos" hx-target="#todos" hx-swap="beforeend"
      hx-on::after-request="if (event.detail.successful) this.reset()">
  <input name="title" placeholder="What needs doing?" required>
  <button>Add</button>
</form>
<ul id="todos" hx-get="/app/todos" hx-trigger="load"></ul>
  • We load two files from a CDN (a public server for files): water.css for simple styles, and htmx.
  • The <style> line draws a line through a todo when its checkbox is checked.

The htmx attributes:

Attribute What it means
hx-get + hx-trigger="load" When the page loads, get the list and put it inside the <ul>.
hx-post on the form Send the form in the background. The page does not reload.
hx-target="#todos" + hx-swap="beforeend" Add the new <li> to the end of the list.
hx-on::after-request After the todo is added, clear the input.
hx-swap="outerHTML" (in the template) Replace the whole row with the new row from the server.

This picture shows one real request. We captured it from the running app when we clicked a checkbox:

One htmx request: PATCH request, HTML response from the hook, row replaced in the page

  1. You click the checkbox. htmx sends PATCH /app/todos/<id>.
  2. The hook switches completed, saves the record and returns the new <li>.
  3. htmx replaces the old <li> with the new one.

The server decides how each row looks. The browser does not need to keep any state.

Step 5: Try it

Open http://127.0.0.1:8090/ in your browser. Add some todos. Check some of them. Delete one.

The todo app running on your computer

Now add a todo with quotes, like Try hx-swap="outerHTML". The server sends &#34;outerHTML&#34;, and the browser shows normal quotes. This is the automatic escaping from Step 3.

Step 6: Look at the data

Each todo is a normal PocketBase record. Open the admin dashboard at http://127.0.0.1:8090/_/ and click todos:

The todos collection in the PocketBase dashboard

You can also see the records in the terminal:

pbc admin records ls todos

pbc admin records ls todos

This is useful for scripts and quick checks.

Before you go live: protect your routes

Our routes use $app directly. This means PocketBase does not check the collection's API rules. The todos collection only allows superusers through /api/. But anyone who can open /app/todos can add and delete todos.

This is OK on your own computer. It is not OK on a public website.

To fix it, add the $apis.requireAuth() middleware to each route:

routerAdd("POST", "/app/todos", (e) => {
  // ...same code as before
}, $apis.requireAuth())

Now a request without a valid login token gets a 401 error.

Then send the user's token with every htmx request:

document.body.addEventListener("htmx:configRequest", (e) => {
  e.detail.headers["Authorization"] = token // for example pb.authStore.token from the PocketBase JS SDK
})

Step 7: Deploy

pbc self upgrade
pbc login
pbc pocketbase deploy --new todos-htmx

What happens:

  • pbc self upgrade updates pbc to the newest version.
  • pbc login connects pbc to your PocketBase Cloud account.
  • The deploy command creates a new instance called todos-htmx. It uploads pb_public, pb_hooks and pb_migrations.
  • The migration from Step 2 creates the todos collection on the new instance.
  • pb_data (your local database) is not uploaded. Your test data stays on your computer.
  • The new instance gets a superuser. Its password is generated and printed only once, so save it.

What's next

Some ideas to try next:

  • Let users edit the title of a todo.
  • Add user login with the PocketBase JS SDK, and protect the routes.
  • Add a user field, so each person sees only their own todos.

Useful links:

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.