How to build APIs and scheduled jobs with Val Town

By

Updated

Tagged: Services

Learn Val Town with practical TypeScript examples: build APIs, store data, automate email, schedule jobs, use AI agents, and understand its limits.

Update, November 10, 2026: Val Town is winding down, and the team plans to open source it. These are the dates:

  • November 10, 2026: new signups and plan upgrades ended, so you can’t follow this tutorial with a new account
  • December 10, 2026: the service goes read-only
  • January 10, 2027: everything else stops
  • February 1, 2027: Val Town is open sourced

If you run something there, move it before December. Val Town has migration guides for Cloudflare, Vercel, Netlify and Render. An HTTP val is a function that takes a Request and returns a Response, so I’d move it to Cloudflare Workers. Export your SQLite and blob data first.

I’m keeping this tutorial online because the code is going to be public. The rest of the post is as I wrote it, and it describes how vals, triggers and storage work in the system being open sourced.

You write a bit of code, hit save, and a second later it’s live on a URL. No server to set up, no deploy step, no config files.

That’s Val Town.

It gives you a place to run small APIs, webhooks, and scheduled scripts, with storage and email already connected.

We’ll start with an endpoint, build a small guestbook API, and put together a scheduled change notification. Then we’ll look at local editing, AI tools, collaboration, and the limits you need to plan around.

If you’re new to the language, my free JavaScript course covers the functions, modules, and asynchronous code used here.

What is Val Town?

Val Town is a place to write JavaScript and TypeScript in the browser. When you save, your code is live on a URL.

The unit of code is called a val. Think of a val as a small folder of code that runs in the cloud. Like a GitHub repo, except it actually runs.

A file inside a val can have a trigger. The trigger is what makes your code run. A file can run through one of these entry points:

  • HTTP: the code runs when someone visits a URL. This is how you build APIs and websites.
  • Cron: the code runs on a schedule.
  • Email: the code runs when an email arrives at a special address.

Val Town also gives you the things you usually need, ready to go: a database (SQLite), file storage, and a way to send email. Nothing to set up.

It runs on Deno, so you write modern JavaScript and TypeScript with web-standard APIs.

Because triggers attach to individual files, a single val can hold an HTTP API, a scheduled task, and shared helper files without turning every helper into a public endpoint:

What makes Val Town code runAn HTTP request, a scheduled time, or incoming email invokes a triggered file. Files can use shared helpers and persistent storage.HTTP requestHTTP handlerScheduled timeCron handlerIncoming emailEmail handlerShared helper filesSQLite or blobstorage

Vals also include version history, branches, and collaboration tools (covered in the val overview). You can start with one file and split things up as your project grows.

What runs on the server?

Your code runs in a hosted Deno runtime. You can make HTTP requests, read environment variables, and use standard web APIs like fetch, Request, and Response.

The editor lives in your browser, but the code handling requests runs on Val Town’s servers, even after you close the tab.

There’s no general filesystem, so anything you want to keep needs to go into SQLite or blob storage. Don’t rely on in-memory arrays or variables between requests, since the next request might hit a fresh worker.

That also affects which npm packages work. Libraries that parse JSON or make HTTP calls are an easy fit, while packages that try to write local files or spawn subprocesses are much harder to run here.

Getting started

Go to val.town and sign up. It’s free, no credit card.

You’ll land in the editor. That’s where you write and run vals, right in the browser.

Your first val

Create a new val and give it an HTTP trigger, by clicking the + button at the top right of the editor and picking HTTP.

An HTTP val is a function. It gets a Request and returns a Response:

export default async function (req: Request): Promise<Response> {
  return new Response('Hello from Val Town!')
}

Save it, copy the HTTP trigger’s URL, and open it. You should see Hello from Val Town!. Val Town handles hosting and HTTPS for you, and pushes your saved code live in around 100ms (that number is deploy speed, while individual request latency depends on what your code does).

If you’ve used the Fetch API or Cloudflare Workers, this is the same Request and Response you already know.

Let’s return JSON instead:

export default async function (req: Request): Promise<Response> {
  return Response.json({ ok: true })
}

Response.json() sets the content type and turns the object into JSON for you.

You can also read from the request. Here we grab a query parameter:

export default async function (req: Request): Promise<Response> {
  const url = new URL(req.url)
  const name = url.searchParams.get('name') || 'stranger'
  return new Response(`Hello, ${name}!`)
}

Add ?name=flavio to your URL and it greets you by name. It’s all standard web APIs, nothing Val Town specific.

Building an API

One route in a plain function is fine. For multiple routes, a framework helps.

Val Town works well with Hono, a tiny web framework. You don’t install it, you import it straight from npm:

import { Hono } from 'npm:hono'

const app = new Hono()

app.get('/', (c) => c.text('Home'))
app.get('/about', (c) => c.text('About'))

export default app.fetch

Look at the last line. app.fetch is a function that takes a Request and returns a Response, which is exactly what an HTTP val expects. So we hand it over as the default export.

You can read route parameters too:

app.get('/users/:name', (c) => {
  const name = c.req.param('name')
  return c.json({ user: name })
})

Visit /users/flavio and you get { "user": "flavio" }.

You can return HTML by setting the content type and returning a string:

export default async function (): Promise<Response> {
  return new Response('<h1>My page</h1>', {
    headers: { 'Content-Type': 'text/html' },
  })
}

Val Town supports JSX too, if you want to build HTML with components. A plain string is enough to start.

Storing data with SQLite

Most apps need to store something. Each val comes with its own scoped SQLite database, shared by all files inside that val. Because Val Town also has an older account-wide database, the exact import path matters.

Use the scoped SQLite import, including /main.ts:

import { sqlite } from 'https://esm.town/v/std/sqlite/main.ts'

Leave /main.ts in there so the guestbook’s tables stay scoped to this val instead of landing in the legacy account-wide database.

Val Town uses Turso for its SQLite service. If SQL is new to you, the free SQL course explains tables and queries in more detail.

Let’s build a tiny guestbook. First, the table:

await sqlite.execute(`create table if not exists messages (
  id integer primary key autoincrement,
  text text not null
)`)

create table if not exists means it’s safe to run every time. It creates the table once and skips it after that.

To add a row, pass your SQL with arguments. The ? is a placeholder for a value:

await sqlite.execute({
  sql: 'insert into messages (text) values (?)',
  args: ['Hello world!'],
})

Always use placeholders for values. They keep user input from messing with your query, which is how SQL injection happens.

To read the data back:

const result = await sqlite.execute('select text from messages order by id desc')
console.log(result.rows)

The rows are in result.rows. Each row is an object with your column names as keys.

Now let’s put the whole API in main.ts with an HTTP trigger. It accepts a JSON message, validates it, and returns the latest 50 entries.

First, add a GUESTBOOK_TOKEN environment variable in the val’s sidebar with a long random string. Both reading and writing check that token, so you can call this endpoint from your own scripts without leaving it open to the internet:

import { sqlite } from 'https://esm.town/v/std/sqlite/main.ts'

await sqlite.execute(`create table if not exists messages (
  id integer primary key autoincrement,
  text text not null
)`)

export default async function (req: Request): Promise<Response> {
  const token = Deno.env.get('GUESTBOOK_TOKEN')
  if (!token) {
    return Response.json({ error: 'Missing server configuration' }, { status: 500 })
  }
  if (req.headers.get('Authorization') !== `Bearer ${token}`) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 })
  }

  if (req.method === 'POST') {
    const body = await req.json().catch(() => null)
    const text = typeof body?.text === 'string' ? body.text.trim() : ''
    if (!text || text.length > 500) {
      return Response.json({ error: 'Send 1 to 500 characters' }, { status: 400 })
    }
    await sqlite.execute({
      sql: 'insert into messages (text) values (?)',
      args: [text],
    })
    return Response.json({ ok: true }, { status: 201 })
  }

  if (req.method !== 'GET') {
    return new Response('Method not allowed', {
      status: 405,
      headers: { Allow: 'GET, POST' },
    })
  }

  const result = await sqlite.execute(
    'select id, text from messages order by id desc limit 50'
  )
  return Response.json(result.rows)
}

To test it from your terminal, set GUESTBOOK_URL to your trigger URL and GUESTBOOK_TOKEN to the same token, then post a message:

curl -i "$GUESTBOOK_URL" \
  -H "Authorization: Bearer $GUESTBOOK_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"text":"Hello from my terminal"}'

You’ll get back an HTTP 201 with {"ok":true}. Fetch the saved messages like this:

curl "$GUESTBOOK_URL" -H "Authorization: Bearer $GUESTBOOK_TOKEN"
Fig 1 · 1/4Saving a guestbook message
A caller sends a message and token

You can also sanity-check the error paths: malformed JSON and blank messages return 400, missing tokens return 401, and a DELETE request with the token returns 405, all without touching the database.

Keep GUESTBOOK_TOKEN on a server or in your terminal, never in client-side JavaScript where any visitor can grab it. If you ever turn this into a public guestbook, add real authentication (or another way to block spam) along with rate limiting, and escape user messages before rendering them as HTML.

One more thing to keep in mind as your table grows: create table if not exists is fine for getting started, but it won’t add new columns to a table that already exists. When your schema changes, switch to a migration. Also remember that rolling back your code doesn’t undo writes already saved in SQLite.

Storing files with blob storage

SQLite is for structured data. When you want to stash a chunk of something, like JSON, an image, or a text file, use blob storage.

Import it the same way:

import { blob } from 'https://esm.town/v/std/blob/main.ts'

The simplest use is reading and writing JSON:

await blob.setJSON('settings', { theme: 'dark' })
const settings = await blob.getJSON('settings')

getJSON returns undefined if the key isn’t there, so you can check for that.

You can list keys, optionally by prefix:

const keys = await blob.list('app_')

And delete one:

await blob.delete('settings')

Just like SQLite, keep /main.ts in the import so you get val-scoped storage instead of the legacy account-wide store (see the blob documentation for details).

Reach for SQLite when you need filtering, sorting, or related records. Use blobs when you’re fetching something by a known key, like an image or a cached API response. Avoid updating shared counters or concurrent state by reading and rewriting a JSON blob, since two requests at the same time can overwrite each other. Use SQLite for that.

Sending email

Val Town can send email in a single call, which is great when a script just needs to tell you something happened:

import { email } from 'https://esm.town/v/std/email'

await email({
  subject: 'Hello from Val Town',
  text: 'This is a test email sent from a val.',
})

By default the email goes to you, the account owner. So sending yourself a notification is as easy as a console.log.

Note: on the free plan you can only email yourself. On Pro you can email anyone, with the to, cc, and bcc fields.

Send HTML instead of text if you want:

await email({
  subject: 'Your daily report',
  html: '<h1>Today</h1><p>All systems normal.</p>',
})

The built-in sender limits what you can put in the from address. If you want to send from your own domain, hook up a provider like Resend and verify your domain there. The email reference lists all the supported fields.

Running code on a schedule

A cron val runs on a timer. Good for reminders, polling a feed, or syncing data.

Give a file a CRON trigger, then write the function that runs:

import { email } from 'https://esm.town/v/std/email'

export default async function () {
  await email({
    subject: 'Good morning!',
    text: 'Time to start the day.',
  })
}

When you add the trigger, you pick the schedule. Either a simple interval like “once an hour”, or a cron expression if you need more control.

This expression runs every two hours, on the first day of the month:

0 */2 1 * *

Cron expressions run in UTC. A fixed UTC hour shifts relative to local time when daylight saving starts or ends. My cron guide explains the fields and time-zone traps.

The function also gets an interval object. Its lastRunAt property holds the previous run time, or undefined on the first run. That’s handy for “what’s changed since last time” jobs:

export default async function (interval: Interval) {
  console.log('Last run was at', interval.lastRunAt)
}

A scheduled change notification

Let’s use a cron file to watch the title of the newest Hacker News story. We’ll store its ID in blob storage and email ourselves whenever a later check sees a new one.

Create watch.ts in a val, attach a cron trigger set to every 15 minutes (so it fits the free plan), and paste this in:

import { blob } from 'https://esm.town/v/std/blob/main.ts'
import { email } from 'https://esm.town/v/std/email'

export default async function () {
  const response = await fetch(
    'https://hn.algolia.com/api/v1/search_by_date?tags=story',
    { signal: AbortSignal.timeout(10000) }
  )
  if (!response.ok) {
    throw new Error(`Story lookup failed: ${response.status}`)
  }

  const data = await response.json()
  const story = data.hits?.[0]
  if (typeof story?.objectID !== 'string' || typeof story?.title !== 'string') {
    throw new Error('Story lookup returned an unexpected response')
  }

  const previous = await blob.getJSON('last-story')
  if (previous === story.objectID) return

  if (previous !== undefined) {
    await email({
      subject: 'A new Hacker News story',
      text: `${story.title}\nhttps://news.ycombinator.com/item?id=${story.objectID}`,
    })
  }

  await blob.setJSON('last-story', story.objectID)
}

The first run just saves a starting point without sending an email. After that, if the ID hasn’t changed, the function returns early. When a new story shows up, it sends the email first and then updates the stored ID.

Fig 2 · 1/4Remembering what a cron already saw
First check: save story 100

Because this only checks the single newest item on each run, stories published in between can slip past. If you want a full digest, fetch a batch of items and keep track of the IDs you’ve already seen in SQLite.

Notice why we send the email before saving the new ID. If sending fails, the stored ID stays as it was, so the next run tries again. The tradeoff is that if sending works and saving fails, you could get a duplicate email on the next run. This snippet also assumes runs don’t overlap. For notifications you can’t afford to double-send, track jobs in a database and pass an idempotency key to your email provider if it supports one.

Val Town’s cron docs cover scheduling syntax and pausing triggers.

Receiving email

This is sending in reverse. An email val gets its own address, and your code runs whenever a message lands there.

Give a file an EMAIL trigger. The function gets the email as its argument:

export default async function (message: Email) {
  console.log('From:', message.from)
  console.log('Subject:', message.subject)
  console.log('Body:', message.text)
}

Copy the exact address shown on the email trigger, or pick an available custom address ending in @valtown.email. Send a message there and the function runs.

The message object has what you’d expect: from, to, subject, text, html, and attachments.

Attachments are File objects, so you can read them directly:

export default async function (message: Email) {
  for (const file of message.attachments) {
    console.log(file.name, file.type)
    const content = await file.text()
    console.log(content)
  }
}

Put sending and receiving together and you can forward support mail to a team channel or pull tasks out of incoming messages. The email trigger reference lists all the fields on message. The subject and body fields can be empty, so check for them before using them.

If you use this for real workflows, treat incoming mail and attachments as untrusted input, and don’t rely on the from address alone to trigger anything sensitive since it’s easy to spoof. If you pass the email to an LLM, treat the whole message as untrusted data so someone can’t sneak instructions into it. And unlike the examples above, don’t log full private emails in production.

Importing npm packages

You saw this with Hono. Val Town supports thousands of npm packages, with no install step. You just import them:

import { Hono } from 'npm:hono'
import dayjs from 'npm:dayjs'

The npm: prefix tells Deno to fetch the package. No package.json, no node_modules.

You can also import JSR packages and other people’s vals through https://esm.town/ URLs. Check the import guide for the full list of supported sources and sandbox limits.

Within your own val, split files up with normal relative imports like import { formatMessage } from './format.ts'. If you want to reuse someone else’s val, copy its module URL from the editor, read through what it does first (especially if your val has secrets in environment variables), and pin a specific version so an upstream edit doesn’t surprise you. Val Town’s version-control documentation covers version pinning and the dependency lockfile.

Keeping secrets out of your code

You’ll often need a secret, like an API key. Don’t hardcode it in your val, because vals can be public.

Set it in your environment variables (there’s a section for this in the Val Town interface), then read it in code:

const apiKey = Deno.env.get('OPENAI_API_KEY')

Check that the variable is set before calling the external API, or a missing key will show up as a confusing auth error later on.

Environment variables stay hidden even when your val’s source code is public, though of course your code can still leak them if you return or log them. If you’re using an organization, environment groups let you share variables across multiple vals.

Private source and private endpoints

Code visibility and HTTP access are two separate settings. A private val can still expose a public HTTP endpoint, and an unlisted val is readable by anyone who has the link:

Source privacy and endpoint access are independentCode access determines who can read the source. App access or handler authentication determines who can call the HTTP endpoint.Val settingsCode accessApp accessPublic, unlisted, orprivate sourceAnyone with the URLRestricted access oneligible plansAdd authenticationin your handler whenneeded

The permissions guide walks through how visibility works. If you want to lock down an endpoint behind a sign-in screen for specific people or email domains, Val Town Access handles that on eligible organization plans. For server-to-server APIs, a bearer-token check like the one in our guestbook is simpler.

For webhooks, you’ll want to verify the sender’s signature instead of putting a login gate in front of it. Check the raw request body if the provider requires it, and store each event ID you process so a retried delivery doesn’t run the same action twice.

Val Town also adds permissive CORS headers by default. You can tighten them for browser apps, while keeping real authentication on the server since anyone with curl or a script can hit the URL directly.

Working from your own editor

The browser editor is great, but sometimes you want your own. Val Town has a CLI called vt for that.

It runs on Deno, so install Deno first, then the CLI:

deno install -grAf jsr:@valtown/vt

Run vt once to log in.

Now create a val as a local folder:

vt create my-api
cd my-api

Edit the files in your editor, then push to go live:

vt push

The best part is vt watch. It syncs your changes every time you save:

vt watch

So you keep the save-and-it’s-live feeling, but in VS Code, Cursor, or wherever you work.

vt feels like git. You can clone a val, make branches, switch between them, and stream logs from your terminal:

vt clone username/valName
vt branch
vt tail

History, branches, and collaboration

Every save creates a version you can inspect in History, compare against earlier versions, and roll back if an edit breaks something.

For bigger changes, create a branch, test it out, and merge it back when you’re happy with it. If you want to contribute to someone else’s public val, remix it and open a pull request. Organizations give teams a shared place to manage projects together.

Code history only tracks your files, not your database. Back up your SQLite data before running a risky migration, and double-check which data and credentials a dev branch points to before testing against live external services.

On the CLI side, vt pull and vt status help when you switch between the browser editor and your local machine, so check status and pull before you overwrite changes on either side. Since vt watch pushes straight to the hosted val on every save, it’s a good habit to switch to a branch while you experiment.

Townie, plugins, and MCP

Townie is Val Town’s in-browser coding agent. It can edit and run files, query storage, read logs, and set up triggers, and its planning mode lets you talk through a change before it touches any code.

If you’d rather use an external AI tool, follow the plugin setup guide for Claude Code, Cursor, Codex, or web chat apps. Once you install it and connect your account, open a fresh session and ask it to list your vals without modifying anything to verify the connection.

Val Town recommends the plugin or MCP integration over vt for AI agents because they expose more platform tools, while vt stays handy when you’re editing files locally yourself.

A good starting prompt for an agent looks like this:

Create a new val with an HTTP endpoint that returns the current time as JSON.
Use no external credentials. Show me the endpoint response and any errors.
Don't change my existing vals or add a cron trigger.

Keep an eye on permissions once an agent can query your database or edit schedules, and try it out on dummy data before pointing it at a real workflow.

MCP also comes up in two different ways here. Val Town’s own MCP server lets an AI agent manage your Val Town account. On the other hand, you can host your own MCP server inside an HTTP val to expose tools from your app. If those tools touch private data, make sure you authenticate those tools first.

Custom domains and websites

An HTTP trigger can return HTML just as easily as JSON. If you’re building a small form, a quick dashboard, or a prototype, you can keep the frontend and API in the same val. Hono handles multiple routes cleanly, and you can use TSX if you’d rather write components than raw HTML strings.

On the free plan you can pick an available val.run subdomain. Paid plans add custom domains: add your domain in Val Town, pick the val that serves it, and copy the DNS records from the dashboard into your DNS provider.

If you’re building a full frontend with a heavy build step, asset pipeline, and a framework-specific adapter, Val Town probably isn’t the smoothest host. A small server-rendered page is where it fits best.

Logs and debugging

When something breaks, start by checking how the file was triggered. An HTTP request, a manual run, an incoming email, and a cron trigger don’t all pass the same inputs.

Log useful context like the HTTP method or the status code from an external API, and keep tokens and private message bodies out of your logs. Also check the status codes your own endpoints return: sending back a 200 with an error message in the body hides failures from any client that checks status codes.

With the guestbook example, test a normal write, an empty list on a fresh val, invalid JSON, and a missing auth header. With the notification example, verify the first run and force a failed API lookup before you turn on the cron schedule.

In that notification example, letting an exception bubble up intentionally leaves the saved ID untouched. If you catch every error and return normally, a failed check looks like it succeeded.

Plans and execution limits

Here are the main differences between the Free and Pro plans from Val Town’s limits page (check the pricing page for current rates):

CapabilityFreePro
Maximum time per run1 minute10 minutes
Shortest cron interval15 minutes1 minute
Log retention3 days10 days
Private vals02,000
Custom domains010
Built-in email recipientsYourselfOther recipients too

The Business plan adds team features and Val Town Access. Townie uses its own separate AI credit allowance rather than pulling from your hosting limits.

Execution time counts wall-clock time, so waiting on a slow external API eats into your limit. Put timeouts on outbound requests, split big jobs into smaller batches, and guard against overlapping runs if a cron job can ever take longer than its schedule interval.

How I would use Val Town

I’d reach for it on small automations that aren’t worth their own deployment project. Things like a scheduled check that reads an RSS feed and sends new links, an HTTP val that catches a webhook and writes a few rows to SQLite, or an email handler that collects forwarded messages for later processing.

Start each one with a manual run, inspect the stored data, and only then turn the trigger on. Keep the first version small enough to understand in one sitting.

If a larger app already lives on Cloudflare Workers, keep its background work beside the rest of that codebase. Pulling Val Town into the same stack splits your credentials and data across one more service to maintain and back up. It makes the most sense when the automation can stand on its own.

Skip it for video processing, a permanent background process, or code that depends on local files and system binaries. Start with short hosted functions paired with a small database and an email notification.

Want me to talk about your product? You can sponsor this site.

Related posts about services: