Skip to content

Instantly share code, notes, and snippets.

@tadeaspetak
Last active January 30, 2022 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tadeaspetak/1881c2e2201887ae4083541090f48134 to your computer and use it in GitHub Desktop.
Save tadeaspetak/1881c2e2201887ae4083541090f48134 to your computer and use it in GitHub Desktop.
// when serving your app
res.cookie("xCsrfToken", generateToken(), { maxAge: 1000 * 3600, sameSite: "strict" });
// on the client
fetch(url, {
headers: {
"content-type": "application/json",
"x-csrf-token": getCookie("xCsrfToken") ?? "",
},
});
// in your sensitive endpoints
if (!req.headers["x-csrf-token"] || req.headers["x-csrf-token"] !== req.cookies["xCsrfToken"]) {
return res.status(400).json({ message: "Invalid CSRF token." });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment