Home / Function/ onRequest() — astro Function Reference

onRequest() — astro Function Reference

Architecture documentation for the onRequest() function in middleware.ts from the astro codebase.

Entity Profile

Dependency Diagram

graph TD
  d4f67aed_a66a_ef1a_76db_e13c238cd7de["onRequest()"]
  9b622ac5_a776_9f9c_f329_0dbaea8866bf["middleware.ts"]
  d4f67aed_a66a_ef1a_76db_e13c238cd7de -->|defined in| 9b622ac5_a776_9f9c_f329_0dbaea8866bf
  style d4f67aed_a66a_ef1a_76db_e13c238cd7de fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

packages/astro/test/fixtures/sessions/src/middleware.ts lines 6–49

export const onRequest = defineMiddleware(async (context, next) => {
  // Skip requests for prerendered pages
  if (context.isPrerendered) return next();

  const { action, setActionResult, serializeActionResult } =
    getActionContext(context);

		console.log(action?.name)

	const actionPayload = await context.session.get(ACTION_SESSION_KEY);

  if (actionPayload) {
    setActionResult(actionPayload.actionName, actionPayload.actionResult);
    context.session.delete(ACTION_SESSION_KEY);
    return next();
  }

  // If an action was called from an HTML form action,
  // call the action handler and redirect to the destination page
  if (action?.calledFrom === "form") {
    const actionResult = await action.handler();

    context.session.set(ACTION_SESSION_KEY, {
      actionName: action.name,
      actionResult: serializeActionResult(actionResult),
    });


    // Redirect back to the previous page on error
    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);
    }
    // Redirect to the destination page on success
    return context.redirect(context.originPathname);
  }

  return next();
});

Subdomains

Frequently Asked Questions

What does onRequest() do?
onRequest() is a function in the astro codebase, defined in packages/astro/test/fixtures/sessions/src/middleware.ts.
Where is onRequest() defined?
onRequest() is defined in packages/astro/test/fixtures/sessions/src/middleware.ts at line 6.

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free