static
Val Town is a collaborative website to build and scale JavaScript apps.
Deploy APIs, crons, & store data – all from the browser, and deployed in milliseconds.
This Val provides a reusable static file server that can be imported into other Val Town projects to serve static assets from the importing project's directory structure.
- Serves static files (HTML, CSS, JS, images, etc.) from the importing project
- Intelligent relative path resolution based on referer headers
- Automatic
index.htmlserving for directory requests - Support for nested directory structures
- Backward compatible with existing usage
Import the createStaticServer function into your HTTP val:
import { createStaticServer } from "https://esm.town/v/peterqliu/static/server.ts";
// Create a static server that serves files from your project
const staticServer = createStaticServer(import.meta.url);
export default async function (req: Request): Promise<Response> {
return staticServer(req);
}
import { Hono } from "https://esm.sh/hono@3.11.7";
import { createStaticServer } from "https://esm.town/v/peterqliu/static/server.ts";
const app = new Hono();
const staticServer = createStaticServer(import.meta.url);
// Serve API routes
app.get("/api/hello", (c) => c.json({ message: "Hello World" }));
// Serve static files for all other routes
app.get("*", async (c) => {
return staticServer(c.req.raw);
});
export default app.fetch;
- Path Resolution: The server analyzes the importing project's
import.meta.urlto determine the correct base directory - Relative Asset Detection: Uses referer headers to intelligently resolve
relative paths (e.g.,
./style.cssfrom/subdir/page.html) - Fallback Logic: Tries multiple resolution strategies and falls back to
serving
index.htmlfor directory requests - File Type Detection: Recognizes common web asset extensions for proper handling
Creates a static file server function.
Parameters:
importMetaUrl: Theimport.meta.urlfrom your importing project
Returns:
(req: Request) => Promise<Response>: A function that handles HTTP requests