Skip to main content
Version: Next (unreleased)

Keeping clients current

A form checks the user's input with the rules it has. Those rules can be old. This guide shows how a server finds out, and how a client catches up without losing what the user typed.

The wire format is in Rule format v1 ("Keeping clients current" and "Rule-set identity"). This page is the how-to.

Why clients fall behind​

  • Bundled rules. The rules were copied into the app at build time (validonce extract, a generated client). A server deploy changes them. The old bundle keeps running until users update.
  • Cached documents. The OpenAPI document sits in a CDN, a service worker or the browser cache.
  • Long-lived tabs. A tab opened yesterday still holds yesterday's rules.
  • Mobile. App store releases take days to reach everyone. Old builds stay in use for months.

The server always checks the rules itself, so nothing invalid gets through. What goes wrong is the user's experience: the form says yes, the server says no, with errors the form never showed. Worse, the form may say no to input the server now accepts.

The header and the decision​

Each request carries the hash of the rule set the client checked it with:

POST /signups
Validonce-Rules: :nVDyv5rCzLnk+vMfLZreejcBwosDQrNxbdAATXKt5nU=:

The value is an RFC 9651 list of byte sequences. A hash is sha256-<base64> as text and :<base64>: in the header. The server compares it with the hash of the rules it enforces on that route and decides:

OutcomeWhen
absentno header, or one that does not parse
currenta submitted hash equals the current hash or an accepted one
staleanything else

A request without the header is always handled. Older clients keep working.

The three modes​

ModeStale request
off (default)handled, no check
reporthandled, with the response header Validonce-Rules-Status: stale; current=:<base64>:
enforceanswered with 412 Precondition Failed before the handler runs

Start with report. Watch how many requests are stale (every backend has a hook for logs or metrics), then move to enforce.

The 412 body is application/problem+json:

{
"type": "https://schemas.metatoy.com/validonce/problems/stale-rules",
"title": "The rules this request was checked with are out of date.",
"status": 412,
"validonce": { "current": "sha256-...", "submitted": ["sha256-..."] },
"rules": { "version": 1, "rules": [] },
"openapi": "https://api.example.test/openapi.json"
}

rules is there when you turn on "include rules", and openapi when you give the server a document URL. Either lets the client recover.

Turn it on in your backend​

All six backends are off by default. Each one takes the same settings: a mode, grace hashes, early notice, inline rules in the 412, and an OpenAPI URL.

ASP.NET Core​

builder.Services.AddValidonce(o =>
{
o.Rules = RulesMode.Enforce; // Off (default), Report or Enforce
o.ExposeCurrentHash = true; // early notice
o.IncludeRulesWhenStale = true; // rules in the 412
o.OpenApiUrl = "https://api.example.test/openapi/v1.json";
o.OnStaleRules = (http, check) => { /* log or count */ };
});

The setting is global. It covers every route that uses WithValidonce() or the MVC filter.

FastAPI​

from fastapi import Depends
from validonce.fastapi import add_rules_exception_handler, rules_check

add_rules_exception_handler(app) # sends the 412 as problem+json

@app.post(
"/signups",
dependencies=[Depends(rules_check(Signup, mode="enforce", expose_current=True, include_rules=True))],
)
def create(signup: Signup): ...

Other arguments: accept_hashes, openapi, on_stale. Without the handler, FastAPI wraps the problem in {"detail": ...}. The client helpers read that form too.

Fastify​

import { validonceHook } from "validonce/fastify";

app.post("/signups", {
schema: { body: signupSchema },
preHandler: validonceHook(signupSchema, {
mode: "enforce",
exposeCurrent: true,
includeRules: true,
openapi: "https://api.example.test/openapi.json",
}),
}, handler);

Other options: acceptHashes, onStale. The hook checks the header before it evaluates the rules.

NestJS​

import { UseFilters, UseGuards } from "@nestjs/common";
import { ValidonceRulesGuard, ValidonceExceptionFilter } from "validonce/nestjs";

@UseGuards(new ValidonceRulesGuard(SignupDto, { mode: "enforce", exposeCurrent: true, includeRules: true }))
@UseFilters(ValidonceExceptionFilter)
@Post("signups")
create(@Body() body: SignupDto) { ... }

The filter sends the 412 as problem+json. The guard runs before the validation pipe.

Go with Huma​

import (
"github.com/metatoy/validonce/go"
"github.com/metatoy/validonce/go/humaonce"
)

huma.Register(api, huma.Operation{
Method: http.MethodPost, Path: "/signups",
Middlewares: huma.Middlewares{humaonce.RulesCheck(signupRules, humaonce.RulesOptions{
Mode: validonce.RulesEnforce,
ExposeCurrent: true,
IncludeRules: true,
OpenAPI: "https://api.example.test/openapi.json",
})},
}, humaonce.Wrap(signupRules, handler))

The middleware runs before Huma parses the input, so a stale request is answered first. The go-playground adapter has no HTTP layer. With it, use humaonce, or call validonce.CheckRules(header, current, accept, time.Now()) in your own handler and answer with validonce.NewStaleRulesProblem(check).

Spring Boot​

validonce.rules.mode=enforce
validonce.rules.expose-current=true
validonce.rules.include-rules=true
validonce.rules.openapi=https://api.example.test/v3/api-docs

The ValidonceRulesInterceptor reads these properties. Like ASP.NET Core, the setting is global.

Grace hashes​

A deploy changes the rules, and clients that were fine a minute ago turn stale. To give them time, accept the previous hash for a while. Each accepted hash can have an expiry (an RFC 3339 datetime with an offset). After that instant it stops counting.

o.AcceptHashes.Add(new AcceptHash("sha256-...", DateTimeOffset.Parse("2026-12-31T00:00:00Z")));
rules_check(Signup, accept_hashes=["sha256-old...", {"hash": "sha256-older...", "until": "2026-12-31T00:00:00Z"}])
validonceHook(schema, { mode: "enforce", acceptHashes: [{ hash: "sha256-...", until: "2026-12-31T00:00:00Z" }] })
Mode: validonce.RulesEnforce,
AcceptHashes: []validonce.AcceptHash{{Hash: "sha256-...", Until: time.Date(2026, 12, 31, 0, 0, 0, 0, time.UTC)}},
validonce.rules.accept-hashes[0].hash=sha256-...
validonce.rules.accept-hashes[0].until=2026-12-31T00:00:00Z

Use grace only when the old and new rules do not disagree in a way that matters. Print the old hash before you deploy (validonce hash, below).

Early notice​

With "expose current" on, every response of a route with rules carries Validonce-Rules-Current: :<base64>:. A page can compare it with its own hash and refresh the rules before the user submits. In the TypeScript client, isBehind(live, response.headers) does the comparison.

CORS​

A browser on another origin has two header rules, and a missing entry fails without an error:

  • Access-Control-Allow-Headers must list Validonce-Rules. Otherwise the browser drops the request header, and the server sees absent for every request.
  • Access-Control-Expose-Headers must list Validonce-Rules-Status and Validonce-Rules-Current. Otherwise scripts cannot read them.

FastAPI:

app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.test"],
allow_methods=["*"],
allow_headers=["Content-Type", "Validonce-Rules"],
expose_headers=["Validonce-Rules-Status", "Validonce-Rules-Current"],
)

Fastify (@fastify/cors):

await app.register(cors, {
origin: "https://app.example.test",
allowedHeaders: ["Content-Type", "Validonce-Rules"],
exposedHeaders: ["Validonce-Rules-Status", "Validonce-Rules-Current"],
});

ASP.NET Core:

policy.WithOrigins("https://app.example.test")
.WithHeaders("Content-Type", "Validonce-Rules")
.WithExposedHeaders("Validonce-Rules-Status", "Validonce-Rules-Current");

NestJS: app.enableCors({ allowedHeaders: [...], exposedHeaders: [...] }) with the same lists. Spring: allowedHeaders and exposedHeaders on your CorsConfiguration. Go: the same two lists in your CORS middleware. Pages on the same origin as the API need none of this.

Client recovery​

The recovery is the same in every framework:

  1. Send the header with each request.
  2. On a 412 stale-rules response, replace the rules (from the body, or by refetching the OpenAPI document).
  3. Re-validate what the user typed, in place, and show the new errors.
  4. Never discard the input. Whether to resubmit is the app's choice: the library does not retry for you.

The core helpers are in validonce:

HelperWhat it does
liveRules(rules, { schema })holds a rule set you can replace: .replace(), .subscribe(), .hash, .rules
rulesHeader(live)the request header: { "Validonce-Rules": ":...:" }
isStaleRules(status, body)true for a stale-rules 412
recoverStaleRules(live, body, { openapi?, fetch? })takes the rules from the 412, or refetches the document, then calls live.replace. Resolves true when the rules changed
isBehind(live, headers)compares Validonce-Rules-Current with live.hash
watchRules(url, live, opts)polls the document; returns a stop function

schema names the OpenAPI component ("Signup"). It is how recoverStaleRules and watchRules find the rules in a document.

React (react-hook-form)​

withRules reads the live rules on every validation, so a replace takes effect on the next check. Subscribe to re-run validation now.

import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect, useMemo } from "react";
import { useForm } from "react-hook-form";
import { isStaleRules, liveRules, recoverStaleRules, rulesHeader, watchRules } from "validonce";
import { withRules } from "validonce/zod";

const live = liveRules(initialRules, { schema: "Signup" });
const schema = withRules(baseSchema, live, { messages });

function SignupForm() {
const form = useForm({ resolver: zodResolver(schema), mode: "onTouched" });

useEffect(() => live.subscribe(() => void form.trigger()), [form]); // re-check the typed values
useEffect(() => watchRules("/openapi.json", live), []); // optional: refresh early

const submit = form.handleSubmit(async (values) => {
const res = await fetch("/signups", {
method: "POST",
headers: { "Content-Type": "application/json", ...rulesHeader(live) },
body: JSON.stringify(values),
});
if (res.status === 412) {
const body = await res.json();
if (isStaleRules(res.status, body)) await recoverStaleRules(live, body); // values are kept; trigger() ran
}
});
// ...
}

Make live once per form (module level, or useRef). Do not create it on every render.

Angular​

validonceGroupValidator accepts a LiveRules, a signal or a function. After a replace, call updateValueAndValidity() on the group.

import { liveRules, rulesHeader, recoverStaleRules, isStaleRules } from "validonce";
import { validonceGroupValidator } from "validonce/angular";

const live = liveRules(rules, { schema: "Signup" });
const group = new FormGroup({ /* controls */ }, { validators: validonceGroupValidator(live) });
live.subscribe(() => group.updateValueAndValidity());

// on submit
this.http.post("/signups", group.value, { headers: rulesHeader(live) }).subscribe({
error: async (e: HttpErrorResponse) => {
if (isStaleRules(e.status, e.error)) await recoverStaleRules(live, e.error);
},
});

With Signal Forms, withRules(Signup, live) from validonce/zod works the same way as in React. Subscribe to live to bump a signal your form reads, or re-run validation yourself.

Vue (VeeValidate)​

<script setup lang="ts">
import { useForm } from "vee-validate";
import { isStaleRules, liveRules, recoverStaleRules, rulesHeader } from "validonce";
import { toVeeSchema } from "validonce/vue";
import { withRules } from "validonce/zod";

const live = liveRules(props.rules, { schema: "Signup" });
const form = useForm({ validationSchema: toVeeSchema(withRules(baseSchema, live, { messages })) });
live.subscribe(() => void form.validate()); // re-check the typed values

const submit = form.handleSubmit(async (values) => {
const res = await fetch("/signups", {
method: "POST",
headers: { "Content-Type": "application/json", ...rulesHeader(live) },
body: JSON.stringify(values),
});
if (res.status === 412) {
const body = await res.json();
if (isStaleRules(res.status, body)) await recoverStaleRules(live, body);
}
});
</script>

Plain HTML and <validonce-form>​

attachRules accepts a LiveRules. On replace it re-validates the form as it is and keeps the values.

import { isStaleRules, liveRules, recoverStaleRules, rulesHeader } from "validonce";
import { attachRules } from "validonce/dom";

const live = liveRules(rules, { schema: "Signup" });
const attached = attachRules(form, live, { messages });

Without a LiveRules, call attached.replaceRules(newRules) yourself.

The <validonce-form> element does the work for you:

const el = document.querySelector("validonce-form")!;
const res = await fetch("/signups", {
method: "POST",
headers: { "Content-Type": "application/json", ...el.rulesHeader() },
body: JSON.stringify(Object.fromEntries(new FormData(form))),
});
if (res.status === 412) await el.recoverStaleRules(await res.json()); // true when the rules changed

recoverStaleRules takes the rules from the body, or refetches rules-url, then re-checks the form and shows the errors. The values stay.

Generated clients​

validonce wrap (and the kubb, Hey API and orval plugins) write the hash of each schema's rules next to the generated code:

import { rulesHeaderFor } from "./schemas.rules";

await fetch("/signups", {
method: "POST",
headers: { "Content-Type": "application/json", ...rulesHeaderFor("Signup") },
body: JSON.stringify(values),
});

_hashes maps each schema name to its sha256-... hash. rulesHeaderFor("Signup", "Address") sends several. Regenerate the file when the server's rules change; that is what the CI check below is for.

A CI check​

A bundled client goes stale the moment the server changes. Catch it in CI.

# print the hash of every schema's rules in an OpenAPI document
npx validonce hash openapi.json

# compare a generated client with the live server; exit 1 when they differ
npx validonce check --against https://api.example.test/openapi.json --rules src/validonce.gen.ts

validonce check exits 0 when every schema's hash matches and 1 on drift. Run it on a schedule against staging or production, and after each server deploy. Use validonce hash to read the old hash before a deploy so you can add it as a grace hash.

Mobile​

React Native can use the TypeScript client as is: liveRules, rulesHeader and recoverStaleRules use only fetch and JSON. Native clients (Swift, Kotlin) are planned; they will compute the same hash and send the same header. Because app store updates are slow, turn on report first, set a grace window for old builds, and move to enforce once the stale share is small.