Skip to content

Keep a value in a cookie

A cookie is sent to the client and comes back with the next request. This program encrypts a value for a cookie and reads it back.

<?nvs
// This program keeps a value in a cookie that the client cannot read or change.
// A real server reads its keys from its configuration. This program makes a new one.
array<secret bytes> $keys = [Core\Crypto::generateKey()];
// `seal` encrypts the value. The result is safe to send as a cookie.
string $cookie = Core\SignedCookie::seal('theme', 'theme=dark', $keys);
// On the next request the client sends the cookie back. `open` returns the value.
// This prints `theme=dark`.
echo Core\SignedCookie::open('theme', $cookie, $keys), "\n";
// A cookie that the client changed throws a `RuntimeError`.
try {
Core\SignedCookie::open('theme', 'x' . $cookie, $keys);
} catch (RuntimeError $error) {
echo "the cookie was changed\n";
}
Output
theme=dark
the cookie was changed

Core\SignedCookie::seal encrypts the value with the first key in the list. open returns the value. If the client changed the cookie, open throws a RuntimeError.

Both members take the cookie’s name. A cookie only opens under the name it was made for.

To send the cookie, use Core\Response::addCookie.

Read Core\SignedCookie for how to change keys without breaking the cookies that clients already have.