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.
Viewing readonly version of main branch: v12View latest version
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;
This val can still be used directly as an HTTP val without importing:
// This val serves static files from its own directory
export default async function (req: Request): Promise<Response> {
// Uses the legacy createServer function
}
- 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
Direct request handler for backward compatibility. Uses this val's own directory.
Parameters:
req: The HTTP request object
Returns:
Promise<Response>: The HTTP response