Requests and responses
Reading requests
The query, headers, cookies and the client IP
import { } from "@senrijs/senri";
import { , } from "@senrijs/senri/cookie";
import { } from "@senrijs/senri/ip";
const = ();
.("/search", (, ) => {
.("page"); // "2" (undefined if missing; c.query() for all)
.("tag"); // ["a", "b"]
...("user-agent"); // read headers from the Request
(, "session"); // a cookie (getCookie(c) for all)
(, "seen", "1");
(); // the client IP (null if unknown)
return "ok";
});Reading the body is covered in Request bodies and limits.
Cookies
They are in @senrijs/senri/cookie, a separate entry point so that apps that do not use them do not bundle them.
getCookie(c, name)/getCookie(c): read one / allsetCookie(c, name, value, options): set one. The defaults arePath=/,HttpOnlyandSameSite=LaxdeleteCookie(c, name, options): delete one
Signed cookies
import { , } from "@senrijs/senri/cookie";
.("/login", async (, ) => {
await (, "user", "42", .);
return "ok";
});
.("/me", async (, ) => {
const = await (, "user", .); // false if tampered with, undefined if missing
return ? `user ${}` : "please log in";
});- The signature is HMAC-SHA256 (Web Crypto). The client can read the value: this detects tampering, it does not encrypt
- Use a random secret of 32 bytes or more, read from an environment variable or
c.env. Pass an array such as["new secret", "old secret"]to sign with the new one and accept signatures from both - The signature includes the cookie name, so copying a value into a cookie with another name does not pass
maxAgeonly asks the browser to drop the cookie. To enforce an expiry, put it in the value and check it
The client IP
getIp(c) from @senrijs/senri/ip returns the client address that the runtime passes. It does not read headers such as X-Forwarded-For, which can be forged. On Cloudflare Workers, it reads CF-Connecting-IP.
Behind a proxy, use a function made with trustProxy().
import { } from "@senrijs/senri/ip";
const = ({ : ["10.0.0.0/8"] }); // or trustProxy({ hops: 1 })
.("/ip", (, ) => () ?? "unknown");- It does not trust the first entry of
X-Forwarded-For: it counts from the right hopscan be forged where requests can reach the app without going through the proxy. Useproxiesthere