Files
sweet/docs/canary/plugins/csrf.md
T
Christian Svensson b7f1abb0d0 test(docs): type check docs code examples (#3180)
This PR adds the initial seeds of type checking the code in all code
blocks for the Markdown Docs.

- Adds a unit test, disabled due to the many remaining errors, that can
help find incorrect code
- Fixes a bunch of syntax errors, type errors, and other code issues
found in the docs

## Future improvements

A lot of remaining issues is mostly related to missing imports, e.g.
`App`, `staticFiles`, `HttpError` etc. There's a couple of different
directions to solve this in future PR's.

- Add explicit imports to all docs examples (may become unnecessarily
verbose)
- Add code to docs code blocks, but with a hint to remove it when
rendering the markdown as HTML
   ```tsx
   import { App } from "fresh";
   // #docs-start

   // Everything above marker above is trimmed away
   const app = new App();
   ```
- Add a `types.d.ts` with "global" types used during type checking, so
globals, imports and so on can be handled globally

I do think that some examples probably should be more explicit with
imports, but it would be overkill for a lot of places such as `app.md`
and `context.md`.
2025-08-05 23:56:04 +02:00

43 lines
1.2 KiB
Markdown

---
description: "Prevent Cross-Site Request Forgery with this middleware"
---
The `csrf()` middleware can be used to add safguard against
[Cross-Site Request Forgery vulnerabilities](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF).
It checks if the user is allowed to load the requested URL based on the values
in the
[`Sec-Fetch-Site`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-Fetch-Site)
header and
[`Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Origin)
header. to HTTP requests. These allow the server to indicate which origins
(domains, scheme or port) other than its own is permitted to load resources
from.
```ts main.ts
import { app, csrf } from "fresh";
const app = new App();
app.use(csrf());
// Specify a single origin
app.use(csrf({ origin: "https://example.com" }));
// Specify multiple origins
app.use(
csrf({ origin: ["https://example.com", "https://trusted.example.com"] }),
);
// Specify multiple origins
app.use(
csrf({ origin: ["https://example.com", "https://trusted.example.com"] }),
);
// Use a function
app.use(
csrf({
origin: (origin) => /^https:\/\/(foo|bar)\.example\.com$/.test(origin),
}),
);
```