CSRF (Cross-Site Request Forgery) protection plugin for Elysia.
bun add elysia-csrfimport { Elysia } from "elysia";
import { csrf } from "elysia-csrf";
const app = new Elysia()
.use(csrf({ cookie: true }))
.get("/form", ({ csrfToken }) => {
return `
<form method="POST" action="/submit">
<input type="hidden" name="_csrf" value="${csrfToken()}" />
<input type="text" name="data" />
<button type="submit">Submit</button>
</form>
`;
})
.post("/submit", ({ body }) => {
return { success: true, data: body };
})
.listen(3000);csrf({
cookie?: boolean | {
key?: string; // Cookie name (default: "_csrf")
domain?: string;
httpOnly?: boolean; // Default: true
maxAge?: number;
path?: string; // Default: "/"
sameSite?: "lax" | "none" | "strict"; // Default: "lax"
secure?: boolean;
signed?: boolean;
};
ignoreMethods?: string[]; // Default: ["GET", "HEAD", "OPTIONS"]
value?: (context: any) => string | undefined; // Custom token extractor
saltLength?: number; // Default: 8
secretLength?: number; // Default: 18
secret?: string;
})By default, tokens are extracted from (in order):
body._csrfquery._csrf- Headers:
csrf-token,xsrf-token,x-csrf-token,x-xsrf-token
Customize with the value option.
Run tests to see examples of all features:
bun testMIT
Contributions are welcome! Please feel free to submit a Pull Request.