Astro’s sessions (and other response-modifying features like cookies/headers) can only be changed before the response is streamed to the browser. Once streaming starts, you’ll get the ResponseSentError (“The response has already been sent to the browser and cannot be altered.”). [Response error; On‑demand features]
From the docs, session access is allowed:
- In
.astro pages/components via Astro.session
- In API endpoints, middleware, and actions via
context.session [Session API; Sessions guide]
But the key constraint is when you call it: it must happen while Astro is still building the page response, not after headers/body have been sent.
To ensure your action can set session data without triggering this error:
-
Do the session write in server-only code that runs during the initial request, not in any client-side/hydrated code.
- For example, call the action from the page’s frontmatter using
Astro.callAction() and let the action use context.session.set(...). [Call actions; Sessions in actions]
---
// src/pages/example.astro
import { actions } from 'astro:actions';
const { data, error } = await Astro.callAction(actions.someAction, { /* input */ });
// inside someAction’s handler, use context.session?.set(...)