Skip to content

Session

Configure a signed session cookie and share small values between Forms pages.

View Markdown

Astro Utils Forms uses a session to store CSRF validation secrets and application values.

The session is stored as an signed JSON Web Token in a browser cookie.

Access the session through Astro.locals inside a page wrapped by WebForms.

src/pages/session.astro
---
import { BindForm, BButton } from "@astro-utils/forms/forms.js";
const { session } = Astro.locals;
session.counter ??= 0;
function increase() {
session.counter++;
}
---
<BindForm>
<p>Current counter: {session.counter}</p>
<BButton onClick={increase}>++</BButton>
</BindForm>

All the configuration is in the middleware creation.

src/middleware.ts
import astroFormsMiddleware from '@astro-utils/forms';
import {sequence} from 'astro/middleware';
export const onRequest = sequence(
astroFormsMiddleware({
secret: import.meta.env.FORMS_SECRET,
session: {
cookieName: 'session',
cookieOptions: {
httpOnly: true,
sameSite: 'lax',
secure: import.meta.env.PROD,
maxAge: 60 * 60 * 24 * 7,
},
},
})
);

maxAge is measured in seconds; the example lasts seven days. Keep FORMS_SECRET stable across restarts. An expired or invalid token starts an empty session; changing the signing secret invalidates existing sessions.

A signature detects tampering; it does not hide the payload from the cookie holder. Store small identifiers and preferences, not passwords or confidential records. Cookies have a limited size and accompany requests, so move growing lists and durable data into application storage. Set secure for HTTPS deployments; local HTTP development needs it disabled.