Resilient Interfaces & Progressive Enhancement

Progressive Enhancement


Learning Objectives

  • You can preserve native POST submission while adding enhanced feedback.
  • You can retain raw rejected text separately from parsed operation values.
  • You can explain the limits of native forms during network loss.

A browser can submit a form and navigate to its response before client JavaScript starts. Progressive enhancement keeps that baseline and adds JavaScript improvements. In Part 4, the forms called Hono through browser code; here a native POST first reaches a SvelteKit page action.

Validate named controls on the server

Consider a language-preference form. Its server-capable application enables server rendering and disables prerendering. The exported actions.default in src/routes/preferences/+page.server.ts handles an ordinary POST:

import { fail, redirect } from "@sveltejs/kit";
import { z } from "zod";
const LanguageSchema = z.enum(["en", "fi"]);
export const actions = {
default: async ({ request }: { request: Request }) => {
const fields = await request.formData();
const submitted = fields.get("language");
const language = typeof submitted === "string" ? submitted : "";
const parsed = LanguageSchema.safeParse(language);
if (!parsed.success) {
return fail(400, { language, error: "Choose English or Finnish." });
}
// This example checks the choice without storing a preference.
redirect(303, "/preferences/checked");
},
};

request.formData() reads named controls. fail(status, data) returns the page with that status and supplies feedback through its form prop. Here Zod runs directly; Hono’s sValidator adapts validation to a different framework.

Keep raw text for redisplay and parsed data for the operation. A schema using .trim() returns a trimmed string while preserving the original variable.

Two values from one field

0 / 5 points

A display-name preview validates a string as follows. Assume the parse succeeds.

const raw = " Mira ";
const parsed = z.string().trim().min(2).safeParse(raw);
if (!parsed.success) {
throw new Error("Invalid display name");
}
const preview = { value: parsed.data, previous: raw };

Which pair is stored in preview.value and preview.previous?

The page can render the original text and feedback:

<script lang="ts">
let { form }: { form?: { language?: string; error?: string } | null } = $props();
</script>
<h1>Check a language preference</h1>
<form method="POST">
<label for="language">Language code</label>
<input id="language" name="language" value={form?.language ?? ""}
aria-describedby={form?.error ? "language-error" : undefined} />
{#if form?.error}<p id="language-error">{form.error}</p>{/if}
<button type="submit">Check language</button>
</form>

Without JavaScript, submitting sv returns the form with that exact text and its validation message. Submitting fi returns a 303 to the fixed result page, which the browser retrieves with GET. Reloading the result page repeats that GET.

SvelteKit’s redirect throws a framework result. Keep it outside a broad catch that would turn it into failure feedback. Use a fixed or carefully validated destination instead of reflecting an arbitrary submitted URL.

Enhance the same form

Import enhance from $app/forms and add use:enhance to the existing POST form. Keep its named, labelled controls and server validation. The native path navigates to the HTML response; the enhanced path applies a serialized action result, including redirect metadata. Both use the same action and destination. See SvelteKit form actions.

Use use:enhance with POST forms targeting SvelteKit page actions. Both native and enhanced server submissions require a reachable server.

Follow a message from rejection to correction

Apply the same pattern to a feedback form. The exercise supplies its schema, form and result page; add validation and enhancement. The checks observe this interaction:

  1. With JavaScript disabled, the visitor enters short in Message, including both spaces on each side, and chooses Check feedback. The form returns the exact text and “Write between 10 and 200 characters.”
  2. Submitting “A useful course comment” reaches the result heading “Feedback checked”, which confirms that the message passed validation.
  3. Once enhancement is ready, submitting invalid text again displays the same server feedback while the current document remains in place.

A native form with feedback

0 / 35 points

Complete the action in routes/feedback/+page.server.ts and add enhancement to the supplied form in routes/feedback/+page.svelte. All seven files are included; open Files (or Show file tree in a narrow editor) to view them. Other files are complete and remain unchanged.

Paths are relative to the supplied SvelteKit application’s src/ directory.

  • routes/feedback/+page.server.ts: complete the action.
  • routes/feedback/+page.svelte: enhance the existing form.
  • lib/feedback-schema.ts: supplied validation schema.
  • routes/+layout.ts: supplied server-rendering settings.
  • routes/+layout.svelte: supplied layout.
  • routes/+page.svelte: supplied entry link.
  • routes/feedback/received/+page.svelte: supplied destination page.

Start with the two editable route files and the schema. The layout, entry link and destination page are references; their implementation is already complete.

Read the named message field. Preserve its exact submitted text; use an empty string for a missing or non-text value. Validate the object { message } with the supplied FeedbackSchema.

On invalid input, return fail(400, { message, error }) with Write between 10 and 200 characters. as the error. The supplied form renders that feedback. On valid input, use redirect(303, "/feedback/received"). This exercise checks feedback validation only.

Use the supplied framework import to enhance the existing native POST form. Retain the named textarea and normal submit button. The form must also work with JavaScript disabled. Do not catch and discard the framework redirect.

Choose Submit solution. Four independent checks award 15 points for native validation, 5 for the accepted redirect, 10 for enhanced feedback and 5 for native controls. An error names the behavior to revisit.

A real mutation also needs the API’s accepted or rejected result. The next lesson connects a protected form action to that authoritative API.

Check Your Understanding

  1. What does the native POST form provide before enhancement?
  2. Why retain raw text separately from parsed values?
  3. What does a 303 change, and what does it establish about storage?
  4. Why does a native form still need the network?