From a5d79ddeb2d592de9eb2468471fdcf3eea5ef730 Mon Sep 17 00:00:00 2001 From: Ben Holmes Date: Tue, 21 May 2024 12:36:58 -0400 Subject: [PATCH] Actions: stop warning about `headers` usage on prerendered routes (#11111) * fix: handle GET requests and prerendered routes * chore: changeset --- .changeset/wild-hounds-repair.md | 5 ++++ .../astro/src/actions/runtime/middleware.ts | 27 +++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 .changeset/wild-hounds-repair.md diff --git a/.changeset/wild-hounds-repair.md b/.changeset/wild-hounds-repair.md new file mode 100644 index 0000000000..f9966f826b --- /dev/null +++ b/.changeset/wild-hounds-repair.md @@ -0,0 +1,5 @@ +--- +"astro": patch +--- + +Fix unexpected `headers` warning on prerendered routes when using Astro Actions. diff --git a/packages/astro/src/actions/runtime/middleware.ts b/packages/astro/src/actions/runtime/middleware.ts index a416974b68..192e7410c4 100644 --- a/packages/astro/src/actions/runtime/middleware.ts +++ b/packages/astro/src/actions/runtime/middleware.ts @@ -3,6 +3,7 @@ import { defineMiddleware } from '../../core/middleware/index.js'; import { ApiContextStorage } from './store.js'; import { formContentTypes, getAction, hasContentType } from './utils.js'; import { callSafely } from './virtual/shared.js'; +import { yellow } from 'kleur/colors'; export type Locals = { _actionsInternal: { @@ -12,6 +13,16 @@ export type Locals = { export const onRequest = defineMiddleware(async (context, next) => { const locals = context.locals as Locals; + if (context.request.method === 'GET') { + return nextWithLocalsStub(next, locals); + } + + // Heuristic: If body is null, Astro might've reset this for prerendering. + // Stub with warning when `getActionResult()` is used. + if (context.request.method === 'POST' && context.request.body === null) { + return nextWithStaticStub(next, locals); + } + // Actions middleware may have run already after a path rewrite. // See https://github.com/withastro/roadmap/blob/feat/reroute/proposals/0047-rerouting.md#ctxrewrite // `_actionsInternal` is the same for every page, @@ -58,6 +69,22 @@ export const onRequest = defineMiddleware(async (context, next) => { return response; }); +function nextWithStaticStub(next: MiddlewareNext, locals: Locals) { + Object.defineProperty(locals, '_actionsInternal', { + writable: false, + value: { + getActionResult: () => { + console.warn( + yellow('[astro:actions]'), + '`getActionResult()` should not be called on prerendered pages. Astro can only handle actions for pages rendered on-demand.' + ); + return undefined; + }, + }, + }); + return next(); +} + function nextWithLocalsStub(next: MiddlewareNext, locals: Locals) { Object.defineProperty(locals, '_actionsInternal', { writable: false,