Bun.CSRF. Tokens are signed with HMAC and include expiration timestamps to limit the token validity window.
Bun.CSRF.generate()
Generate a CSRF token. The token contains a cryptographic nonce, a timestamp, and an HMAC signature, encoded as a string.
secret(string, optional) — The secret key used to sign the token. If not provided, Bun generates a random in-memory default secret (unique per thread).options(object, optional):
| Option | Type | Default | Description |
|---|---|---|---|
expiresIn | number | 86400000 | Milliseconds until the token expires. Defaults to 24 hours. |
encoding | string | "base64url" | Token encoding format: "base64", "base64url", or "hex". |
algorithm | string | "sha256" | HMAC algorithm: "sha256", "sha384", "sha512", "sha512-256", "blake2b256", or "blake2b512". |
string — the encoded token.
Bun.CSRF.verify()
Verify a CSRF token. Returns true if the token is valid and has not expired, false otherwise.
token(string, required) — The token to verify.options(object, optional):
| Option | Type | Default | Description |
|---|---|---|---|
secret | string | (auto) | The secret used to sign the token. If not provided, uses the same in-memory default as generate(). |
maxAge | number | 86400000 | Maximum token age in milliseconds, independent of the token’s own expiresIn. |
encoding | string | "base64url" | Must match the encoding used during generate(). |
algorithm | string | "sha256" | Must match the algorithm used during generate(). |
boolean
Using with Bun.serve()
A typical pattern is to generate a token when rendering a form, embed it in a hidden field, and verify it when the form is submitted.
Default secret
If you omit thesecret parameter in both generate() and verify(), Bun uses a random secret generated once per thread. This is convenient for single-thread applications but won’t work across multiple servers, workers, or after a restart.