spaserver

package module
v1.7.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 19, 2026 License: AGPL-3.0 Imports: 10 Imported by: 0

README

einherjar/spa-server

version license go

A shield wall holds because every warrior knows their position. The SPA asks only for the wall — not for every soldier's name.

code.nochebuena.dev/einherjar/spa-server is a container-first HTTP server for single-page applications and progressive web apps. It serves static assets directly and falls back to index.html for navigation routes that do not resolve to a file — the standard SPA routing contract — while a missing asset returns 404 rather than the HTML shell.

The module ships as a ready-to-use Docker base image. Deploying a SPA to a container requires a single COPY instruction. No nginx, no custom configuration, no index.html redirect logic to maintain.


Container usage

FROM code.nochebuena.dev/einherjar/spa-server:v1.7.1
COPY dist/ /srv/www/

That is the complete Dockerfile for a production SPA container. It runs as an unprivileged user and serves /srv/www on port 8080.

COPY dist/ /srv/www/ is correct for Vite and CRA, which emit index.html at the root of dist/. Angular's application builder instead emits dist/<project>/browser/ (with index.html inside browser/, next to 3rdpartylicenses.txt), so copy that subdirectory — otherwise no index.html lands at the root and every request falls through to a 404:

FROM code.nochebuena.dev/einherjar/spa-server:v1.7.1
COPY dist/my-app/browser/ /srv/www/

Environment variables

Variable Default Description
EINHERJAR_SPA_PORT 8080 TCP port the server listens on
EINHERJAR_SPA_STATIC_DIR /srv/www Path to the directory containing index.html and assets
EINHERJAR_LOG_LEVEL INFO Log level: DEBUG, INFO, WARN, ERROR

Health endpoint

GET /health returns 200 OK with a JSON body consistent with all Einherjar health responses:

{"status":"UP","components":{}}

503 Service Unavailable is never returned — if the process is alive, it is healthy. Wire /health directly to your container liveness and readiness probes.


Routing behaviour

Request Result
/app.js — file exists Served directly with correct Content-Type
/assets/logo.png — file exists Served directly
/dashboard — no file, Accept: text/html index.html served (SPA router handles it)
/ — directory index.html served (directory listing is disabled)
/main.js — no file, has an extension 404 — a missing asset is not masked as HTML
/api/x — no file, Accept: application/json 404 — a non-HTML client is not handed index.html

The fallback to index.html is deliberately scoped to navigation requests (no file extension, and Accept includes text/html or */*). A request for a missing asset returns 404 instead of index.html, so a broken deploy fails at the first request rather than delivering the SPA shell as JavaScript (Unexpected token '<').


Caching

Cache-Control is set per file, correct for Vite, CRA and Angular alike:

File Cache-Control
index.html no-cache — revalidated every load, so a new deploy is never masked
Service workers (ngsw.json, ngsw-worker.js, sw.js, service-worker.js, safety-worker.js, workbox-*.js) no-cache — a client is never pinned to a superseded release
Content-hashed assets (main.4f8a2b1c.js, index-DkJf3x9a.js, …) public, max-age=31536000, immutable
Everything else (favicon.ico, icons/, verbatim assets) public, max-age=3600

A hashed filename is detected by a trailing hash-like token (≥8 alphanumerics including a digit) before the extension — a heuristic whose only failure mode is a missed year-long cache, never staleness.

Every response also carries X-Content-Type-Options: nosniff.


Dependency graph

contracts  (zero dependencies)
    ↑
  core
    ↑
spa-server  (contracts, core, stdlib only)

No external dependencies beyond the Go standard library.


Verification

cd spa-server/
go build ./...
go vet ./...
go test ./...
gofmt -l .

A shield wall holds because every warrior knows their position. The SPA asks only for the wall — not for every soldier's name.

Documentation

Overview

Package spaserver provides a lifecycle-managed HTTP server for serving single-page applications (SPA) and progressive web apps (PWA) from a container.

Overview

The server delivers static assets from a configurable directory and falls back to index.html for any request path that does not map to an existing file — the standard SPA routing contract. A health endpoint is included at /health with the same JSON wire format used across all Einherjar modules.

Lifecycle

NewServer returns a [lifecycle.Component] that integrates directly with [launcher.New]. Server.OnInit builds the HTTP mux. Server.OnStart begins serving in a goroutine. Server.OnStop performs a graceful shutdown.

cfg := spaserver.DefaultConfig()
srv := spaserver.NewServer(logger, cfg)

lc := launcher.New(logger)
lc.Append(srv)
if err := lc.Run(); err != nil {
    log.Fatal(err)
}

Configuration

All fields are read from environment variables:

  • EINHERJAR_SPA_PORT — listen port (default: 8080)
  • EINHERJAR_SPA_STATIC_DIR — path to the directory containing index.html and assets (default: /srv/www)
  • EINHERJAR_LOG_LEVEL — log level: DEBUG, INFO, WARN, ERROR (default: INFO)

Container usage

The module ships as a ready-to-use base image. A downstream SPA Dockerfile only needs to copy the built assets:

FROM code.nochebuena.dev/einherjar/spa-server:v1.0.0
COPY dist/ /srv/www/

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Port is the TCP port the server listens on.
	Port int `env:"EINHERJAR_SPA_PORT" envDefault:"8080"`
	// StaticDir is the filesystem path that contains index.html and all assets.
	StaticDir string `env:"EINHERJAR_SPA_STATIC_DIR" envDefault:"/srv/www"`
}

Config holds the server configuration. All fields are populated from environment variables by DefaultConfig.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config populated from environment variables, falling back to safe defaults when variables are unset.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is a lifecycle-managed HTTP server that serves a single-page application. Register with [launcher.New] via Append — it implements [lifecycle.Component].

func NewServer

func NewServer(logger logging.Logger, cfg Config) *Server

NewServer returns a Server configured by cfg.

func (*Server) OnInit

func (s *Server) OnInit() error

OnInit builds the HTTP mux and configures the underlying http.Server.

func (*Server) OnStart

func (s *Server) OnStart() error

OnStart begins serving HTTP requests in a background goroutine. The TCP listener binds synchronously so a port conflict surfaces immediately.

func (*Server) OnStop

func (s *Server) OnStop() error

OnStop performs a graceful shutdown, waiting up to 10 seconds for in-flight requests to complete before forcefully closing connections.

Directories

Path Synopsis
cmd
spa-server command
Package health provides the /health HTTP handler for spa-server.
Package health provides the /health HTTP handler for spa-server.
Package spa provides the HTTP handler that serves a single-page application.
Package spa provides the HTTP handler that serves a single-page application.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL