0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-16 21:46:22 -05:00

Actions: stop warning about headers usage on prerendered routes (#11111)

* fix: handle GET requests and prerendered routes

* chore: changeset
This commit is contained in:
Ben Holmes 2024-05-21 12:36:58 -04:00 committed by GitHub
parent 3cc3e2ccba
commit a5d79ddeb2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 32 additions and 0 deletions

View file

@ -0,0 +1,5 @@
---
"astro": patch
---
Fix unexpected `headers` warning on prerendered routes when using Astro Actions.

View file

@ -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,