FeaturesTemplatesShowcaseTownie
AI
BlogDocsPricing
Log inSign up
panphora

panphora

hyperclay

a single-tenant version of hyperclay
Public
Like
hyperclay
Home
Code
4
ARCHITECTURE.md
DEBUG_GUIDE.md
README.md
H
index.ts
Branches
1
Pull requests
Remixes
1
History
Environment variables
3
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.
Sign up now
Code
/
README.md
Code
/
README.md
Search
9/4/2025
Viewing readonly version of main branch: v69
View latest version
README.md

Hyperclay-Compatible Self-Updating Page - Hono Edition

A clean, secure implementation of a self-updating HTML page with email authentication, built for Val.town and fully compatible with Hyperclay.js. Successfully refactored with Hono framework for improved architecture and maintainability.

Quick Setup Guide

1. Remix This Val

Click the remix button in Val.town to create your own copy of this project.

2. Set Environment Variables

In your Val.town settings, add these environment variables:

  • ADMIN_EMAIL - Your email address (required for authentication)
  • APP_NAMESPACE - Optional namespace for storage (defaults to "default")

3. Deploy

The val is already configured as an HTTP trigger. Just save and it's live at your Val.town URL.

4. Test Public Access

Visit your Val.town URL (e.g., https://yourusername-yourval.web.val.run) - you should see the Hyperclay starter template in read-only mode.

5. Authenticate as Admin

  1. Go to /auth/edit (e.g., https://yourusername-yourval.web.val.run/auth/edit)
  2. Enter your admin email address
  3. Check your email for the magic link
  4. Click the magic link to authenticate

6. Start Editing

After authentication, return to your main URL. You should now see:

  • Edit controls and buttons
  • Contenteditable areas become editable
  • Auto-save functionality (Ctrl+S)
  • Access to version history at /versions

7. Share Your App

Your public URL is now ready to share! Others will see the read-only version while you can edit by authenticating.


Recent Improvements

✅ Hono Framework Migration

  • Battle-tested framework: Migrated from vanilla Request/Response to Hono for better reliability
  • Declarative routing: Clean app.get(), app.post() syntax instead of manual URL parsing
  • Built-in cookie helpers: setCookie(), getCookie(), deleteCookie() with proper security
  • Middleware architecture: Modular authentication and logging middleware
  • Better error handling: Framework-level error boundaries and consistent error responses

✅ Security Enhancements

  • Server-side cookie setting: All cookies now set securely on the server with proper attributes
  • Eliminated client-side cookie vulnerabilities: No more JavaScript-based cookie setting
  • Enhanced cookie security: All cookies include Secure, SameSite=Lax, and proper expiration
  • HttpOnly session cookies: Session cookies cannot be accessed by client-side JavaScript

✅ Architecture Refactor

  • 700+ line monolithic function → Clean, modular Hono route handlers
  • Manual URL parsing → Declarative Hono routing system
  • Repetitive cookie handling → Built-in Hono cookie helpers
  • Mixed concerns → Separation via middleware and focused handlers
  • Hard to test → Isolated, testable route handlers

Features

  • Email Authentication: Secure admin access via magic links
  • Hono Framework: Modern, lightweight web framework for better maintainability
  • Hyperclay Integration: Full compatibility with Hyperclay.js editing features
  • Version History: Automatic versioning of all changes with viewing capability
  • Reset Functionality: Admin-only dangerous reset that clears all content and history
  • Clean Architecture: Well-organized Hono routes with middleware-based auth
  • Persistent Storage: Uses Val.town blob storage for reliability
  • Namespace Support: Environment-configurable for multiple deployments
  • Security-First: Server-side cookie management with proper security attributes

Environment Variables

Set these in your Val.town environment:

  • ADMIN_EMAIL: The email address that can authenticate for edit access (required)
  • APP_NAMESPACE: Namespace for storage keys, allows multiple deployments (optional, defaults to "default")
  • DEBUG: Set to "true" to enable detailed server-side logging for debugging authentication issues (optional)

URL Structure

Public URLs (No Authentication Required)

  • GET / - Serves the HTML document
  • GET/POST /auth/view - Switches to view mode (clears admin cookies)

Protected URLs (Email Authentication Required)

  • GET/POST /auth/edit - Email auth flow (GET shows form, POST sends magic link)
  • GET /auth/verify?token=... - Magic link verification endpoint

Admin-Only URLs (Requires Valid Session)

  • POST /save/app - Saves HTML content (used by Hyperclay.js)
  • GET /versions - View version history of all saved documents
  • POST /reset-dangerous - DANGEROUS: Resets HTML to default template and clears all version history

User Flows

Public User Experience

  1. Visit your Val.town URL
  2. See content in read-only mode
  3. No edit controls visible (handled by Hyperclay.js)

Admin Authentication Flow

  1. Visit /auth/edit
  2. Enter your email (must match ADMIN_EMAIL)
  3. Check email for magic link
  4. Click link → authenticated and redirected to main page
  5. Edit controls now visible and functional

Admin Editing Experience

  1. After authentication, visit main URL
  2. Hyperclay.js detects admin cookies (automatically set server-side for authenticated users)
  3. Content becomes editable with edit-mode-* attributes
  4. Changes auto-save via Ctrl+S or periodic saves
  5. Visit /versions to see change history

Technical Implementation

Authentication Flow

  • Custom email authentication system using magic links
  • Sessions stored in Val.town blob storage with 30-day expiration
  • Server-side cookie management: Hyperclay-compatible cookies (currentResource=app, isAdminOfCurrentResource=true) set securely on the server
  • Sessions auto-extend on activity
  • Enhanced security: All cookies include proper security attributes (Secure, SameSite=Lax, HttpOnly for sessions)

Storage Strategy

  • Main document stored as {namespace}_app
  • Versions stored as {namespace}_app_version_{number}
  • Version counter stored as {namespace}_app_version_count
  • Reset endpoint clears main document (resets to default) and all version history
  • All storage uses Val.town blob storage for persistence

Architecture Design

  • Handler-based routing: Each endpoint has a dedicated handler function
  • Modular utilities: Reusable functions for auth, storage, and HTML operations
  • Clean separation: Auth logic, business logic, and routing properly separated
  • Error boundaries: Consistent error handling throughout the application
  • Maintainable code: Easy to understand, test, and extend

Hyperclay.js Integration

  • Loads Hyperclay.js from CDN (always latest version)
  • Follows standard Hyperclay patterns for edit mode detection
  • Supports all edit-mode-* attributes (contenteditable, show, onclick, etc.)
  • Auto-save posts to /save/app endpoint

Security Model

  • Server-side cookie security: All cookies set with proper security attributes
  • Magic link email authentication: Gates session creation securely
  • HttpOnly session cookies: Cannot be accessed by client-side JavaScript
  • Secure transmission: All cookies marked as Secure for HTTPS-only transmission
  • CSRF protection: SameSite=Lax provides cross-site request forgery protection
  • Session validation: Save endpoint validates active sessions before accepting changes
  • No client-side secrets: All sensitive operations happen server-side

Default HTML Template

The system starts with a Hyperclay starter template that includes:

  • Tailwind CSS integration
  • Hyperclay.js starter kit
  • Template selection interface
  • Dark theme styling
  • Responsive design

Development

Testing the Implementation

  1. Set your ADMIN_EMAIL environment variable
  2. Deploy to Val.town
  3. Visit your Val.town URL to see public view
  4. Visit /auth/edit to test authentication flow
  5. Make edits and verify auto-save functionality
  6. Check /versions to see version history

Reset Functionality

The /reset-dangerous endpoint provides a way to completely reset the application state:

⚠️ WARNING: This is a destructive operation that cannot be undone!

  • What it does: Resets the HTML content to the default template and deletes all version history
  • Access: Only available to authenticated admin users via POST request
  • Usage: Send a POST request to /reset-dangerous
  • Response: JSON with success/error message and count of cleared versions

Example usage with curl:

curl -X POST https://your-val-url.web.val.run/reset-dangerous \ -H "Cookie: session=your-session-id"

Or via JavaScript in the browser console (when authenticated):

fetch('/reset-dangerous', { method: 'POST' }) .then(r => r.json()) .then(console.log);

Customization

  • Modify DEFAULT_HTML to change the starting template
  • Adjust session expiration in the auth system (currently 30 days)
  • Add additional validation in saveHTML if needed
  • Extend version history with metadata (timestamps, etc.)

Architecture Benefits

Security

  • Server-side cookie management: Eliminates client-side cookie vulnerabilities
  • Proper security attributes: All cookies include necessary security flags
  • HttpOnly sessions: Session cookies protected from XSS attacks
  • Email-based authentication: No passwords to manage or compromise
  • Protected admin endpoints: All sensitive operations require valid sessions

Maintainability

  • Modular design: Each feature has its own focused handler
  • Clean separation: Auth, routing, and business logic properly separated
  • Consistent patterns: Standardized error handling and response formats
  • Easy to extend: Adding new features doesn't require modifying existing handlers

Reliability

  • Persistent blob storage: Data survives server restarts
  • Automatic version history: Never lose previous versions
  • Comprehensive error handling: Graceful degradation on failures
  • Session management: Automatic session extension and cleanup

Simplicity

  • Single file implementation: Everything in one place for easy deployment
  • No database setup required: Uses Val.town's built-in blob storage
  • Minimal configuration: Just set your email address
  • Standard patterns: Follows established web development conventions

Troubleshooting

Common Issues

  1. Can't authenticate: Check ADMIN_EMAIL environment variable matches exactly
  2. Magic link not received: Check spam folder, verify email service is working
  3. Magic link expired: Links expire after 15 minutes, request a new one
  4. Changes not saving: Verify you're authenticated (check browser cookies for session)
  5. Version history empty: Versions are only created after first save
  6. Edit mode not working: Ensure Hyperclay.js is loading (check browser console)

Debug Steps

  1. Enable debug logging: Set DEBUG=true in environment variables
  2. Check browser cookies for session and isAdminOfCurrentResource=true
  3. Verify network requests to /save/app are successful
  4. Test authentication flow by visiting /auth/edit
  5. Check Val.town logs for server-side errors (especially with DEBUG=true)
  6. Verify ADMIN_EMAIL environment variable is set correctly

Detailed Debugging Guide

For comprehensive debugging steps and troubleshooting, see DEBUG_GUIDE.md.

This implementation provides a robust, secure, and user-friendly self-updating page system that integrates seamlessly with Hyperclay.js while maintaining clean architecture and security best practices.

FeaturesVersion controlCode intelligenceCLI
Use cases
TeamsAI agentsSlackGTM
ExploreDocsShowcaseTemplatesNewestTrendingAPI examplesNPM packages
PricingNewsletterBlogAboutCareersBrandhi@val.townStatus
X (Twitter)
Discord community
GitHub discussions
YouTube channel
Bluesky
Terms of usePrivacy policyAbuse contact
© 2025 Val Town, Inc.