Skip to content

Commit

Permalink
Actions: stop warning about headers usage on prerendered routes (#1…
Browse files Browse the repository at this point in the history
…1111)

* fix: handle GET requests and prerendered routes

* chore: changeset
  • Loading branch information
bholmesdev committed May 21, 2024
1 parent 3cc3e2c commit a5d79dd
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/wild-hounds-repair.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro": patch
---

Fix unexpected `headers` warning on prerendered routes when using Astro Actions.
27 changes: 27 additions & 0 deletions packages/astro/src/actions/runtime/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down

0 comments on commit a5d79dd

Please sign in to comment.