Backend

This folder contains the server-side code for the MolstarViewer application.

Structure

backend/
├── index.ts          # Main HTTP entry point for Val Town
└── README.md         # This file

(Serves files from frontend/ folder at project root)

Entry Point

index.ts is the main HTTP handler that Val Town calls when your val receives requests.

It uses Hono (a lightweight web framework) to:

  • Serve static files from the /frontend/* directory
  • Return /frontend/index.html for all other routes (enabling client-side routing)
  • Handle errors and show full stack traces for debugging

How It Works

import { Hono } from "jsr:@hono/hono@4"; import { serveFile } from "https://esm.town/v/std/utils@85-main/index.ts"; const app = new Hono(); // Error handling app.onError((err, c) => { throw err; // Shows full stack traces }); // Serve frontend files app.get("/frontend/*", (c) => serveFile(c.req.path, import.meta.url)); // SPA: serve index.html for all other routes app.get("*", (c) => serveFile("/frontend/index.html", import.meta.url)); export default app.fetch; // Val Town entry point

Key Points

  1. Static File Server: This is purely a static file server - no server-side rendering or API routes
  2. SPA Pattern: All routes return /frontend/index.html, letting React handle routing client-side
  3. No Database: Currently no database or state storage (add backend/database/ if needed)
  4. File Naming: index.ts exports app.fetch as default, which Val Town recognizes as an HTTP handler
  5. Clean Structure: All frontend assets (HTML, React, components) are in the frontend/ folder

Adding Features

To add API routes:

// Add before the catch-all route app.get("/api/structures", async (c) => { return c.json({ structures: [...] }); });

To add a database:

Create backend/database/ folder with:

  • migrations.ts - Schema definitions
  • queries.ts - Database query functions

To organize routes:

Create backend/routes/ folder for modular route handlers.

Val Town Specifics

  • Val Town recognizes backend/index.ts as an HTTP handler because it exports a default fetch handler
  • import.meta.url gives context about the current val's location
  • serveFile utility handles reading files from the project and setting correct content types
  • All paths are relative to the project root (e.g., /frontend/* not ../frontend/*)