View val on Val Town|docs.md (for LLMs)
@std/utils is a collection of utilities for Val Town, including reading files, serving static content, getting Val Town metadata, and more.
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.
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.
(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).(request: Request) => Response | Promise<Response> that serves static files with correct Content-Type headers. Returns 404 for missing files.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);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.
File not found: <path> if the file doesn't exist.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);Gets the HTTP endpoint URL for the currently running val or a specific file in the val.
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.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 endpointGets 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.
{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.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.emailLists 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.
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
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));Gets the ID of a val.
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"Lists files in a specific directory path within the current val.
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.
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));Fetches and transpiles TypeScript/JavaScript code from esm.town URLs.
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);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.
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);
});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.
export default (req: Request) => serveFile(req, "/index.html");Determines the appropriate MIME type for a file based on its extension.
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"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.
// In your (never-cached) HTML shell:
<script type="module" src={immutableFileUrl("/frontend/index.tsx")} />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
c.req.path)// Route the reserved prefix to it in your Hono app:
app.get("/__immutable/*", (c) => serveImmutableFile(c.req.path));Parses Val Town metadata from an import.meta.url.
{
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)
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: {...} }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.
import.meta.url of the current filetrue if the file is the main entry point, false otherwiseimport { 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
}Creates a test runner that displays test results as an HTML page with badges and detailed output.
{ name, tests, before?, after? } objects. Each test is { name, function } — throw to fail, return to pass.(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.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);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.
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" },
});
});