From f7bdfd3cb816dc16b128d031461f98ddc2cbfa5a Mon Sep 17 00:00:00 2001 From: badbl0cks <4161747+badbl0cks@users.noreply.github.com> Date: Thu, 22 Jan 2026 14:05:29 -0800 Subject: [PATCH] Add middleware to persist form actions in session and follow POST-REDIRECT-GET form submission pattern --- src/middleware.ts | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/middleware.ts diff --git a/src/middleware.ts b/src/middleware.ts new file mode 100644 index 0000000..106aec8 --- /dev/null +++ b/src/middleware.ts @@ -0,0 +1,46 @@ +import { defineMiddleware } from "astro:middleware"; +import { getActionContext } from "astro:actions"; +import { randomUUID } from "node:crypto"; + +export const onRequest = defineMiddleware(async (context, next) => { + if (context.isPrerendered) return next(); + + const { action, setActionResult, serializeActionResult } = + getActionContext(context); + + const currentAction = await context.session?.get("currentAction"); + + if (currentAction) { + const { actionName, actionResult } = JSON.parse(currentAction); + setActionResult(actionName, actionResult); + + context.session?.delete("currentAction"); + return next(); + } + + if (action?.calledFrom === "form") { + const actionResult = await action.handler(); + + context.session?.set( + "currentAction", + JSON.stringify({ + actionName: action.name, + actionResult: serializeActionResult(actionResult), + }), + ); + + if (actionResult.error) { + const referer = context.request.headers.get("Referer"); + if (!referer) { + throw new Error( + "Internal: Referer unexpectedly missing from Action POST request.", + ); + } + return context.redirect(referer); + } + + return context.redirect(context.originPathname); + } + + return next(); +});