Open a session

This guide shows you how to open a session, save a change to it, hash passwords, and set cookies.
Cow’s session helper stores session data in SQLite. Create a private data directory next to your site directory, then open the database and session:
account.cow
<?js
import { sqlite } from 'cow:sqlite'
import { session } from 'cow:web'

const db = await sqlite(__dirname + '/../data/site.sqlite')
const visitor = await session(db, req, res)
?>
<p>Hello, <?= h(visitor.data.name || 'friend') ?>.</p>
Output — /account, on a first visit
<p>Hello, friend.</p>
Open or change the session before the page writes response output, so that Cow can send the session’s cookie headers.
Warning: Use HTTPS for real logins.

Save a change explicitly

Include the session’s CSRF token in the form, in a field named csrf:
Form field
<input type="hidden" name="csrf" value="<?= h(visitor.csrfToken) ?>">
Session update
const values = await req.formData()
visitor.verify(values)
visitor.update({ ...visitor.data, name: 'Clover' })
verify() checks submitted values. If the token does not match, the request ends with a 403 response.
update() saves an explicit snapshot. It does not silently save every mutation to visitor.data. Concurrent changes can report a conflict, with status 409 and the code COW_SESSION_CONFLICT.

Hash passwords

Use the password helpers when you build authentication.
Warning: Store the returned hash, never the original password.
Password helpers
import { hashPassword, verifyPassword } from 'cow:web'

const encoded = await hashPassword(password)
const matches = await verifyPassword(candidate, encoded)
These helpers are pieces for building authentication, not a complete login service. The example applications also show authorization, session changes, and form protection.

Set and read cookies

Cookie helpers
import { cookies, setCookie } from 'cow:web'

const theme = cookies(req).theme || 'light'
setCookie(res, 'theme', 'light', { path: '/', sameSite: 'Lax' })
Cookie options include path, lifetime, secure, and HttpOnly.
Warning: Set secure cookies deliberately when you host behind a proxy. Cow does not automatically trust forwarded headers.