served

Articles ·

SQLite from a serverless function

A serverless function has no disk to keep a database on. With SQLite behind an HTTP API, fetch is all it needs: a client of ten lines, and how to keep the requests few.

Give a serverless function a SQLite database it can reach with fetch. The database lives in Served, so the function can keep data between runs without relying on its local filesystem.

Use this pattern on Cloudflare Workers, Vercel or AWS Lambda with the HTTP client already in your runtime.

The whole client

One function of ten lines. This is a complete program: save it as shop.mjs and run it with Node 18 or later.

const API = "https://api.served.dev/v1/databases";

async function served(key, path, body) {
  const resp = await fetch(API + path, {
    method: "POST",
    headers: { Authorization: `Bearer ${key}` },
    body: JSON.stringify(body),
  });
  const data = await resp.json();
  if (!resp.ok) throw new Error(`${data.error.code}: ${data.error.message}`);
  return data;
}

const key = process.env.SERVED_KEY;

await served(key, "", { name: "shop" });
await served(key, "/shop/query", {
  sql: `CREATE TABLE IF NOT EXISTS orders (
          id INTEGER PRIMARY KEY, item TEXT, total INTEGER)`,
});
await served(key, "/shop/query", {
  sql: "INSERT INTO orders (item, total) VALUES (?, ?)",
  args: ["kettle", 2400],
});

const { rows } = await served(key, "/shop/query", {
  sql: "SELECT item, total FROM orders",
});
console.log(JSON.stringify(rows));
[["kettle",2400]]

In a function

Create the database and its tables once, from your own machine or a deploy step. The function then only runs queries. On Cloudflare Workers, with the same served function above it in the file:

export default {
  async fetch(request, env) {
    const { rows } = await served(env.SERVED_KEY, "/shop/query", {
      sql: "SELECT item, total FROM orders ORDER BY id DESC LIMIT ?",
      args: [20],
    });
    return Response.json(rows);
  },
};

The key is a secret of the Worker: npx wrangler secret put SERVED_KEY. On Vercel and Lambda it is an environment variable, read as process.env.SERVED_KEY, and the rest is the same.

One request for each thing you do

Send related statements together to make one network trip. An array of statements runs as one transaction, with a result for each:

const { results } = await served(env.SERVED_KEY, "/shop/query", [
  { sql: "INSERT INTO orders (item, total) VALUES (?, ?)", args: ["teapot", 3100] },
  { sql: "SELECT count(*), sum(total) FROM orders" },
]);
const [orders, total] = results[1].rows[0];

If one statement fails, none of them is kept. That is also how you do anything that must be all or nothing, since a function cannot hold a transaction open between requests. SQLite over HTTP says more about why.

Give the function its own key

A key can be limited to some databases. A function that only uses shop can have a key that only opens shop. Keep the key on the server side: a key that is sent to a browser can be read by whoever uses the page.

What you end up with

A function with no state of its own, and a database you can take home. GET /v1/databases/shop/download gives you shop.db, an ordinary SQLite file, to open on your own machine with the tools you already have.

Served is hosted SQLite. Real SQLite behind an HTTP API, $5 a month, and the file is yours to download whenever you like.

Get started Read the docs