Val Town Utils Documentation

View val on Val Town|docs.md (for LLMs)Val Town badge

@std/utils is a collection of utilities for Val Town, including reading files, serving static content, getting Val Town metadata, and more.

💡 What is the entrypoint?

Many functions below accept an optional metaImportUrl parameter that defaults to the entrypoint. The entrypoint is the import.meta.url of the file that Val Town executed — the HTTP handler that received a request, the cron job that fired, the email handler that received a message, or the script you clicked "Run" on. Val Town sets this automatically via Deno.env.get("VALTOWN_ENTRYPOINT"), so you almost never need to pass it yourself. The main reason to pass import.meta.url explicitly is when you're calling these functions from a different val than the one that was triggered.


staticHTTPServer

source

Creates a simple static HTTP server that serves HTML, CSS, and JS files from your val.

This is the easiest way to deploy a static site or single-page app on Val Town: drop an index.html (plus any CSS/JS/assets) into your val and export default staticHTTPServer().

The server automatically serves /index.html for root requests and handles all other file paths. It also exposes a /source route that redirects to the val's source code on Val Town, so visitors can always click through to view how a page was built.

If you need a little custom routing (an API route, a redirect) but mostly want a static server, pass a fetch handler as the second argument. It's tried first on every request: return a Response to handle the request yourself, or return null/undefined to fall through to the static server (and the /source redirect). This is just the fetch standard — pass a plain function, or any framework's handler (e.g. Hono's app.fetch). See the second example.

Asset files are served via serveImmutableFile, so they get immutable version-addressed browser caching automatically (bare paths 302 into /__immutable/<version>/, and publishing the val bumps the version, invalidating every cached file at once); / and /index.html always serve fresh.

Arguments

metaImportUrl (string): the import.meta.url to determine which val to serve files from. Defaults to the entrypoint
handler (FetchHandler): A fetch handler (request: Request) => Response | null | undefined (or a promise thereof). Tried before static serving: return a Response to handle the request, or null/undefined to defer to the static server and the /source redirect. Pass a plain function or any framework's fetch handler (e.g. Hono's app.fetch).

Returns

((request: Request) => Response | Promise<Response>): A fetch-compatible handler function (request: Request) => Response | Promise<Response> that serves static files with correct Content-Type headers. Returns 404 for missing files.

Example

import { staticHTTPServer } from "https://esm.town/v/std/utils/index.ts";

// Most common usage - serves files from current val, plus a /source redirect
export default staticHTTPServer();

// Explicit val specification
export default staticHTTPServer(import.meta.url);

// Mostly static, but with a bit of custom routing.
// Pass a fetch handler: return a Response to handle a request,
// or null/undefined to fall through to static file serving.
import { staticHTTPServer } from "https://esm.town/v/std/utils/index.ts";

export default staticHTTPServer(import.meta.url, (req) => {
  const { pathname } = new URL(req.url);
  if (pathname === "/api/hello") return Response.json({ hello: "world" });
  return null; // defer to the static server (index.html / assets / /source)
});

// Any framework works too, since app.fetch is just a fetch handler.
import { Hono } from "npm:hono@4.11.9";
import { staticHTTPServer } from "https://esm.town/v/std/utils/index.ts";

const app = new Hono();
app.get("/api/hello", (c) => c.json({ hello: "world" }));
// Return 404s as null so unmatched routes fall through to the static server.
app.notFound(() => null as any);

export default staticHTTPServer(import.meta.url, app.fetch);

readFile

source

Reads the contents of a file.

Use readFileTranspiled if you need transpiled JavaScript for execution, like in a browser.

Note: Val Town doesn't provide direct file system access. This function uses the Val Town API to read your val files, allowing Val Town to more efficiently provide a scalable serverless runtime.

Arguments

path (string): the file path to read (with or without leading slash)
metaImportUrl (string): the import.meta.url to determine which val to read from. Defaults to the entrypoint

Returns

(Promise<string>): Promise that resolves to the raw file contents as a string. Throws File not found: <path> if the file doesn't exist.

Example

import { readFile } from "https://esm.town/v/std/utils/index.ts";

// Most common usage - reads raw TypeScript from current val
const content = await readFile("/utils/helper.ts");
console.log(content); // Contains TypeScript with type annotations

// Explicit val specification
const content2 = await readFile("/README.md", import.meta.url);
console.log(content2);

httpEndpoint

source

Gets the HTTP endpoint URL for the currently running val or a specific file in the val.

Arguments

path (string): the file path to get the endpoint for. Defaults to the currently running endpoint.
metaImportUrl (string): the import.meta.url to determine which val the file belongs to. Defaults to the entrypoint

Returns

(Promise<string>): Promise that resolves to the full HTTP URL for the endpoint. Throws File not found: <path> if the file doesn't exist, or No HTTP endpoint available for file: <path> if it isn't an HTTP file.

Example

import { httpEndpoint } from "https://esm.town/v/std/utils/index.ts";

const endpoint = await httpEndpoint();
console.log(endpoint); // Returns the full HTTP URL for the endpoint

emailAddress

source

Gets the email address for a file with an email trigger in the val.

Note: This function does not work for vanity email addresses. It only works for the UUID version.

Arguments

path (string): the file path to get the email address for
metaImportUrl (string): the import.meta.url to determine which val the file belongs to. Defaults to the entrypoint

Returns

(Promise<string>): Promise that resolves to the email address in format: {username}-{fileIdWithoutDashes}@valtown.email. Throws File not found: <path> if the file doesn't exist, or File does not have email trigger: <path> if it isn't an email file.

Example

import { emailAddress } from "https://esm.town/v/std/utils/index.ts";

// Get the email address for a file with email trigger
const email = await emailAddress("/handlers/processEmail.ts");
console.log(email); // Returns: username-fileid@valtown.email

listFiles

source

Lists all files in the current val with their metadata.

Note: Val Town doesn't provide direct file system access. This function uses the Val Town API to list your val files, enabling a more scalable serverless runtime.

Arguments

metaImportUrl (string): the import.meta.url to determine which val to list files from. Defaults to the entrypoint

Returns

Promise<{
  name: string;
  id: string;
  path: string;
  version: number;
  updatedAt: string;
  type: "directory" | "file" | "interval" | "http" | "email" | "script";
  links: {
    self: string;
    html: string;
    module: string;
    endpoint?: string;
    email?: string;
  };
}[]>

Promise that resolves to an array of file metadata objects — see the signature above for the full type

Example

import { listFiles } from "https://esm.town/v/std/utils/index.ts";

// Most common usage - lists files from current val
const files = await listFiles();
files.forEach((file) => console.log(file.path));

// Explicit val specification
const files2 = await listFiles(import.meta.url);
files2.forEach((file) => console.log(file.path));

getValId

source

Gets the ID of a val.

Arguments

metaImportUrl (string): the import.meta.url to determine which val to get the ID for. Defaults to the entrypoint

Returns

(Promise<string>): Promise that resolves to the val ID as a string

Example

import { getValId } from "https://esm.town/v/std/utils/index.ts";

// Get the val id for the val this code is in
const id = await getValId();
console.log(id); // Returns: "bb8f592e-f528-11ef-b06d-569c3dd06744"

listFilesByPath

source

Lists files in a specific directory path within the current val.

Arguments

path (string): the directory path to list files from (with or without leading slash)
metaImportUrl (string): the import.meta.url to determine which val to list files from. Defaults to the entrypoint

Returns

Promise<{
  name: string;
  id: string;
  path: string;
  version: number;
  updatedAt: string;
  type: "directory" | "file" | "interval" | "http" | "email" | "script";
  links: {
    self: string;
    html: string;
    module: string;
    endpoint?: string;
    email?: string;
  };
}[]>

Promise that resolves to an array of file metadata objects (same shape as listFiles). Throws File not found: <path> if the val has no such path.

Example

import { listFilesByPath } from "https://esm.town/v/std/utils/index.ts";

// List files in a specific directory
const frontendFiles = await listFilesByPath("frontend/");
frontendFiles.forEach((file) => console.log(file.path));

fetchTranspiledJavaScript

source

Fetches and transpiles TypeScript/JavaScript code from esm.town URLs.

Arguments

url (string): the esm.town URL to fetch (e.g., "https://esm.town/v/username/valname@version-branch/file.ts")

Returns

(Promise<string>): Promise that resolves to the transpiled JavaScript code as a string

Example

import { fetchTranspiledJavaScript } from "https://esm.town/v/std/utils/index.ts";

const code = await fetchTranspiledJavaScript(
  "https://esm.town/v/std/utils@85-main/index.ts"
);
console.log(code);

serveFile

source

Serves a file from the val as an HTTP Response with the correct Content-Type header.

A file that doesn't exist is logged and answered with a 404 rather than thrown: a missing asset is ordinary traffic for a static server (favicons, bots, stale links), not an exception. Every other failure still throws.

Arguments

path (string): the file path to serve
metaImportUrl (string): the import.meta.url to determine which val to serve from. Defaults to the entrypoint

Returns

(Promise<Response>): Promise that resolves to an HTTP Response with the file content and appropriate Content-Type header, or a 404 naming the file if it doesn't exist

Example

import { serveFile } from "https://esm.town/v/std/utils/index.ts";

// In a Hono app - most common usage
app.get("/assets/*", async (c) => {
  return await serveFile(c.req.path);
});

// Explicit val specification
app.get("/assets/*", async (c) => {
  return await serveFile(c.req.path, import.meta.url);
});

serveFile

source

Same as above, but also accepts the incoming Request first — the argument order of Deno's serveFile, and a common guess. The request itself is unused.

Returns

(Promise<Response>)

Example

export default (req: Request) => serveFile(req, "/index.html");

getContentType

source

Determines the appropriate MIME type for a file based on its extension.

Arguments

path (string): the file path to get the content type for

Returns

(string): The MIME type string (e.g., "text/html", "application/json")

Example

import { getContentType } from "https://esm.town/v/std/utils/index.ts";

console.log(getContentType("index.html")); // "text/html; charset=utf-8"
console.log(getContentType("script.ts")); // "text/javascript"
console.log(getContentType("data.json")); // "application/json; charset=utf-8"

immutableFileUrl

source

Makes your val's frontend faster by letting browsers cache its files immutably — repeat visits load them straight from the cache instead of re-downloading them. Works by putting the val's current version in the URL: immutableFileUrl("/frontend/index.tsx") → "/__immutable/45/frontend/index.tsx". Publishing the val bumps the version, which changes every URL at once — browsers refetch each file exactly once, and caches never go stale.

Use it in your (never-cached) HTML shell to stamp the client entry script and favicon, and route /__immutable/* to serveImmutableFile. The version prefixes the whole path, so the entry's relative imports stay in versioned space — the entire client graph ends up immutably cached.

Arguments

path (string): the file path to stamp (e.g. "/frontend/index.tsx" or "/logo.png")
metaImportUrl (string): the import.meta.url to determine which val's version to stamp. Defaults to the entrypoint

Returns

(string): The version-addressed URL (e.g. "/__immutable/45/frontend/index.tsx")

Example

// In your (never-cached) HTML shell:
<script type="module" src={immutableFileUrl("/frontend/index.tsx")} />

serveImmutableFile

source

Makes your val's frontend faster by letting browsers cache its files immutably — repeat visits load them straight from the cache instead of re-downloading them. Serves the version-addressed URLs that immutableFileUrl produces; publishing the val bumps the version, which changes every URL, so caches invalidate automatically on every publish.

Handles the three cases: - current version (/__immutable/45/...) → serves the file with Cache-Control: immutable - any other version → plain 404: old URLs die when you publish (like Next.js build assets — a stale open tab that lazy-loads gets a 404; a reload fixes it) - no /__immutable/ prefix → 302 into versioned space — so an existing plain asset route can point here too: <script src="/frontend/index.tsx"> keeps working at the cost of one redirect per page view. Note the redirect lands on /__immutable/..., so that route must exist as well (see the example); stamp the URL with immutableFileUrl in your HTML shell to skip the redirect entirely

Arguments

path (string): the requested path (e.g. c.req.path)
metaImportUrl (string): the import.meta.url to determine which val (and version) to serve from. Defaults to the entrypoint

Returns

(Promise<Response>): Promise resolving to the file Response, a 302 into the current version, or a 404 for non-current versions and missing files (the 404 carries no cache header)

Example

// Route the reserved prefix to it in your Hono app:
app.get("/__immutable/*", (c) => serveImmutableFile(c.req.path));

parseVal

source

Parses Val Town metadata from an import.meta.url.

Arguments

metaImportUrl (string): the import.meta.url to parse. Defaults to the entrypoint

Returns

{
  username: string;
  name: string;
  version: string;
  branch: string;
  path: string;
  links: {
    self: {
      latest: string;
      pinned: string;
      val: string;
    };
    module: {
      latest: string;
      pinned: string;
      val: string;
      valPinned: string;
    };
  };
}

A Val object with username, name, version, branch, path, and links (containing self and module URL variants)

Example

import { parseVal } from "https://esm.town/v/std/utils/index.ts";

const val = parseVal(import.meta.url);
console.log(val);
// Output: { username: "username", name: "valname", version: "1", branch: "main", path: "", links: {...} }

isMain

source

Checks if the current file is the main entry point of the val.

This is a replacement for import.meta.main which is not available in Val Town's environment.

Arguments

metaImportUrl (string): the import.meta.url of the current file

Returns

(boolean): true if the file is the main entry point, false otherwise

Example

import { isMain } from "https://esm.town/v/std/utils/index.ts";

if (isMain(import.meta.url)) {
  // Code that doesn't run if this file is imported
  // Useful for testing functions near their definitions
}

testServer

source

Creates a test runner that displays test results as an HTML page with badges and detailed output.

Arguments

testGroups ({}): Array of { name, tests, before?, after? } objects. Each test is { name, function } — throw to fail, return to pass.

Returns

((req: Request) => Promise<Response>): A (req: Request) => Promise<Response> handler. Returns an HTML results page; an SVG badge at /badge.svg; or JSON at /results.json — { passed, total, duration, groups: [{ name, passed, total, tests: [{ name, pass, duration, message? }] }] }, with message set to the error for failing tests.

Example

import { testServer } from "https://esm.town/v/std/utils/index.ts";

const myTests = [{
  name: "Math tests",
  tests: [
    { name: "addition", function: () => { if (1 + 1 !== 2) throw new Error("Math is broken"); } },
    { name: "subtraction", function: () => { if (5 - 3 !== 2) throw new Error("Wrong result"); } }
  ]
}];

export default testServer(myTests);

hotReload

source

Wraps an HTTP handler to enable hot reload during development.

When a val is served on a .val.run domain, this wrapper: 1. Injects a small script into HTML responses that long-polls for version changes 2. Handles the long-poll endpoint (/__vt_hot_reload) 3. Actively checks the Val Town API for new versions of the current branch 4. When a new version is deployed, the client detects the change and reloads the page

On custom domains (non .val.run), the handler passes through unmodified.

Arguments

handler ((req: Request) => any): Your HTTP fetch handler

Returns

((req: Request) => Promise<Response>): A wrapped handler with hot reload support

Example

import { hotReload } from "https://esm.town/v/std/utils/index.ts";

export default hotReload(async (req: Request) => {
  return new Response("<html><body><h1>Hello!</h1></body></html>", {
    headers: { "Content-Type": "text/html" },
  });
});