---
title: A server for your app
description: When your app needs a server, and how your Studio agent builds one with Bun for the course's host.
---

# A server for your app

Try your app on two devices: your phone and a laptop. Add something on one. Should the other show it, or should someone else see it? Then your app needs a server. It needs one when:

- people see each other's data: a shared list, a feed, a leaderboard, messages,
- people sign in, so their data follows them from device to device. See [Accounts in your app](accounts.guide.md),
- the app keeps something that has to last, or that only the server should decide, like a score nobody can fake.

Otherwise, keep your app in the browser, with its data in `localStorage`. A single-player game or a tool for one person needs nothing more. When a feature needs a server, your agent adds one and tells you why.

---

<!-- id: limits -->

## What the host can't do yet

Your server runs on the course's own small computer. That keeps it safe and free, and it has limits:

- **No internet from your server.** It reaches npm while it installs packages, and nothing else. Your page calls APIs instead: one that needs no key, like MLB's stats, with `fetch`, and one that needs a key through the course, as [APIs with a key](keys.guide.md) shows.
- **Keys only for reading data,** so no payments, email or texts.
- **Bun only,** with its data in SQLite: no Python, Postgres or Redis.
- **AI from the page,** through the course, as [AI in your app](ai.guide.md) shows.

If your project needs one of these, ask Mark. Open **Ada** at the bottom of your screen, switch **To** from Ada to Mark, and say what your app needs and why. Your agent will tell you when you've hit one.

---

<!-- id: shape -->

## The shape of a Bun app

The course hosts your app with [Bun](https://bun.com). A Bun app here keeps its pages as they are and adds an API beside them:

- a `package.json` whose `start` script runs the server: `{ "scripts": { "start": "bun server.ts" } }`,
- a `server.ts` that calls `Bun.serve`, which listens on the port the host gives it (`PORT`),
- your pages, scripts, styles and pictures, served as they are, so they work just as they did,
- its data in a SQLite file under the folder the host keeps between deploys, `DATA_DIR`.

```ts
// server.ts
import { Database } from "bun:sqlite"
import { mkdirSync } from "node:fs"

const data = process.env.DATA_DIR ?? "./data"
mkdirSync(data, { recursive: true })
const db = new Database(`${data}/app.sqlite`, { create: true, strict: true })
db.run("PRAGMA journal_mode = WAL")
db.run("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, text TEXT NOT NULL, created TEXT NOT NULL)")

// The browser's own files: pages, scripts, styles, pictures, sounds, fonts and data files.
const PUBLIC = /\.(html?|css|m?js|json|csv|txt|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf|mp3|wav|ogg|m4a|mp4|webm|glb|gltf|bin)$/i
const HIDDEN = new Set(["docs", "data", "node_modules", "package.json"])

Bun.serve({
  port: Number(process.env.PORT ?? 3000),
  routes: {
    "/health": new Response("ok"),
    "/api/notes": {
      GET: () => Response.json(db.query("SELECT * FROM notes ORDER BY id DESC").all()),
      POST: async (req) => {
        const { text } = await req.json()
        if (typeof text !== "string" || !text.trim()) return Response.json({ error: "Write something first." }, { status: 400 })
        const note = db.query("INSERT INTO notes (text, created) VALUES ($text, $created) RETURNING *").get({ text: text.trim(), created: new Date().toISOString() })
        return Response.json(note, { status: 201 })
      },
    },
  },
  // Everything else is the app's own files, exactly as they are.
  async fetch(req) {
    let path = decodeURIComponent(new URL(req.url).pathname).slice(1)
    if (path === "" || path.endsWith("/")) path += "index.html"
    const parts = path.split("/")
    if (!PUBLIC.test(path) || parts.some((part) => part.startsWith(".") || HIDDEN.has(part))) return new Response("Not found", { status: 404 })
    const file = Bun.file(path)
    return (await file.exists()) ? new Response(file) : new Response("Not found", { status: 404 })
  },
})
```

The page asks the API with `fetch("/api/notes")` where it used `localStorage` before. Moving an app that already works in the browser is the same: keep its files, add `package.json` and `server.ts`, then move what's shared from `localStorage` into tables, one feature at a time. Sample data the app started with becomes rows the server adds when its table is empty.

An app written in TypeScript or JSX imports `index.html` as a route instead (`import homepage from "./index.html"`, then `"/": homepage`), and Bun bundles the scripts and styles it links. Files the code loads by name, like `images/dragon.webp` in a script, still need the `fetch` above.

---

<!-- id: built-in -->

## Bun first, packages later

Bun has what a first server needs built in, so your app needs no packages from npm:

| You need | Bun has |
| --- | --- |
| Pages and an API | `Bun.serve` with `routes`, and `req.params` for `/api/notes/:id` |
| A database | `bun:sqlite` |
| Passwords | `Bun.password.hash` and `Bun.password.verify` |
| Remembering who's signed in | `req.cookies` |
| Files | `Bun.file` and `Bun.write`, under `DATA_DIR` |
| Live updates | WebSockets in `Bun.serve` |

When you do need a package, your agent adds it with `bun add` in the Studio's sandbox, which writes the lockfile the host installs from, and tells you what it's for: every package is someone else's code your app depends on.

---

<!-- id: safe -->

## Keeping it safe

- **SQL takes parameters,** like `$text` above, never text pasted into a query.
- **Secrets stay out of your repo.** A key or a password never goes into a file.
- **Check what people send:** the server decides what's allowed, not the page.
- **Passwords are hashed** with `Bun.password`, never stored as they were typed.

---

<!-- id: try -->

## Trying it

Your app runs in the Studio's App tab with your files as they are, committed or not. It runs on the course's host, at its own preview address, so what you see is what the host really does. After a change it says it's starting, and the last version stays up until the new one is ready. When your agent tries your app, it uses this same server.

Serve your pages from their files, as above. The Studio can only see into pages it can find in your files, so a page your server writes as a string runs fine, but its errors stay hidden and your agent can't try it.

**When something goes wrong,** the App tab says so under your app: it didn't start, or a request failed. **Ask to fix** hands that to your agent, which can read what your server printed.

**The preview has its own data.** It starts empty, stays between changes, and is apart from what's online. Anyone with the address can open it, so keep private things out of it.

**When a table changes,** `CREATE TABLE IF NOT EXISTS` keeps the old table. In the preview, your agent asks you, then clears the data and starts over. Once your app is online, real people's data stays, so `server.ts` changes the table when it starts:

```ts
const columns = db.query("PRAGMA table_info(notes)").all() as { name: string }[]
if (!columns.some((column) => column.name === "done")) db.run("ALTER TABLE notes ADD COLUMN done INTEGER NOT NULL DEFAULT 0")
```

**Signing in** needs its cookie set a certain way to work in the App tab. See [Accounts in your app](accounts.guide.md#try).

**Going online** deploys your latest commit to your app's real address, with its own data. Your data stays between deploys.
