CSRF protection plugin for Elysia with cookie-based token storage
npm install elysia-csrf  
CSRF (Cross-Site Request Forgery) protection plugin for Elysia.
``bash`
bun add elysia-csrf
`typescript
import { Elysia } from "elysia";
import { csrf } from "elysia-csrf";
const app = new Elysia()
.use(csrf({ cookie: true }))
.get("/form", ({ csrfToken }) => {
return
;
})
.post("/submit", ({ body }) => {
return { success: true, data: body };
})
.listen(3000);
`Configuration
`typescript
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;
})
`Token Extraction
By default, tokens are extracted from (in order):
1.
body._csrf
2. query._csrf
3. Headers: csrf-token, xsrf-token, x-csrf-token, x-xsrf-tokenCustomize with the
value option.Testing
Run tests to see examples of all features:
`bash
bun test
``MIT
Contributions are welcome! Please feel free to submit a Pull Request.