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:<?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><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:<input type="hidden" name="csrf" value="<?= h(visitor.csrfToken) ?>">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.
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.