stnd.buildSTANDARD MANUAL2026-07-15

@stnd/server

@stnd/server

Standard server-side infrastructure, data orchestrations, and edge utilities.

ELI5

Every website needs to answer questions like “is this user logged in?”, “is this request allowed to come from that other website?”, and “what error message do I show when something breaks?”. This package is the small set of answers Standard gives to those questions, so every app doesn’t reinvent auth/CORS/error handling from scratch. (This was Francis’s very first module — the CORS piece, because “I understand nothing about this and wanted it handled fast.”)

Install: already included when you use @stnd/core — nothing extra to add.

Use it (the 90% case — protecting an API route):

import { getSession } from "@stnd/server/auth";
import { Errors, withErrorHandling } from "@stnd/server/errors";

export const POST = withErrorHandling(async ({ request, locals }) => {
  const session = await getSession(request, locals.env.JWT_SECRET, "stnd_session");
  if (!session) throw Errors.authRequired();
  // ...do the thing
});

That’s it — sessions and clean error responses, without writing the plumbing.

Overview

@stnd/server is the backend core of the Standard framework. It provides base orchestrations for request contexts, data validation, and business logic execution. Built for edge-first runtimes (e.g., Cloudflare Workers, Astro middleware, Page Functions), it contains utilities for authentication, CORS, error boundaries, and internationalization.


1. Domain Infrastructure

The package promotes clean separation between data layers and application logic through two core abstract classes:

StandardRoot

The global coordinator of a request. It maps edge variables (databases, KV caches, env variables) and visitor profiles into a single context.

import { StandardRoot } from "@stnd/server";
import { Visitor } from "./Visitor";

export class Root extends StandardRoot {
  public visitor!: Visitor;

  // Custom extension: attach app-specific services
  static async enter(context: any): Promise<Root> {
    const root = await super.enter(context) as Root;
    
    // Wire local KV bindings
    root.kv = root.env?.MY_APP_KV;
    
    // Initialize the Visitor model from headers/session cookies
    root.visitor = await Visitor.fromUrl(root, context);
    
    return root;
  }
}

StandardModel

The base class for all business data structures. Provides automatic serialization (stripping root circular references) and KV cache integration.

import { StandardModel } from "@stnd/server";
import type { Root } from "./Root";

interface NoteData {
  id: string;
  title: string;
  content: string;
}

export class Note extends StandardModel<NoteData, Root> {
  // strip circular parent references for clean serialization in Svelte/React templates
  toJSON() {
    return this.raw;
  }

  // Automatic caching with Cloudflare KV
  static async getCachedNote(root: Root, noteId: string): Promise<Note | null> {
    const cacheKey = `note:${noteId}`;
    
    const data = await this.withCache<NoteData>(
      root,
      cacheKey,
      async () => {
        // Fetch from D1 SQL database on cache miss
        return await root.db.prepare("SELECT * FROM notes WHERE id = ?").bind(noteId).first();
      },
      300 // TTL of 5 minutes (300 seconds)
    );

    return data ? new Note(root, data) : null;
  }
}

2. Submodule API Reference

/auth (Authentication & Sessions)

JWT token encoding/decryption and HTTP session management.

  • signJWT(payload, secret): Generates a JWT token.
  • verifyJWT(token, secret): Decrypts and validates a JWT token.
  • getSession(request, secret, cookieName): Reads and parses session cookies.
  • createSession(data, secret): Encodes a new session payload.
import { signJWT, verifyJWT, getSession } from "@stnd/server/auth";

const token = await signJWT({ userId: "user_123" }, env.JWT_SECRET);
const session = await getSession(request, env.JWT_SECRET, "stnd_session");

/errors (Error Boundary Framework)

Standardized error mapping that handles HTTP semantics gracefully on the edge.

  • Errors: A collection of pre-defined error builders throwing custom semantic errors (e.g., authRequired()notFound()forbidden()badRequest()).
  • handleError(error): Translates internal exceptions into standard HTTP responses.
  • withErrorHandling(handler): Higher-order wrapper to secure API endpoints.
import { Errors, withErrorHandling } from "@stnd/server/errors";

export const POST = withErrorHandling(async ({ request, locals }) => {
  const user = locals.user;
  if (!user) {
    throw Errors.authRequired("You must be logged in to plant a note.");
  }
  // handle note creation...
});

/cors (Cross-Origin Setup)

Enforces header security boundaries in middleware or server routes.

  • getCorsHeaders(origin): Generates security headers for approved origins.
  • handleCorsPreflight(request): Intercepts and answers standard CORS preflight requests (OPTIONS).
import { handleCorsPreflight, getCorsHeaders } from "@stnd/server/cors";

export async function OPTIONS({ request }) {
  return handleCorsPreflight(request);
}

/i18n (Language Detection)

Auto-detects locales from HTTP parameters, headers, or cookies.

  • detectLanguage(request): Inspects Accept-Language headers and cookies to match supported languages.
  • getSupportedLanguages(): Lists the active languages supported by standard themes.

Notes / Observations

(jot down anything noticed here — quirks, gotchas, ideas)

Todo

  • [ ] Nothing tracked yet.