From 870e0aaca71e58b281da8bc58123d3c4f87c68e0 Mon Sep 17 00:00:00 2001 From: pawciobiel <1190054+pawciobiel@users.noreply.github.com> Date: Wed, 25 Mar 2026 20:10:30 +0100 Subject: [PATCH] Update README with CSRF token handling instructions in JS SPA Added instructions for setting CSRF token in backend templates. Signed-off-by: pawciobiel <1190054+pawciobiel@users.noreply.github.com> --- README.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/README.md b/README.md index d768c81..af5cf2f 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,26 @@ try { } ``` +It's not always feasible to send form fields to SPA applications and HTTP headers may not always be available +from JS (first load), so one can use a backend template with a script tag to set CSRF token to be used on a first load. +The care must be taken to not HTMLescape or unicode-escape that token: + +```hmtl + +``` + +```go +token := csrf.Token(r) +tokenJSON, err := json.Marshal(token) + if err != nil { + panic(err) + } + tmpl.Execute(w, map[string]any{ + "CSRFToken": template.JS(tokenJSON), + ... + }) +``` + If you plan to host your JavaScript application on another domain, you can use the Trusted Origins feature to allow the host of your JavaScript application to make requests to your Go application. Observe the example below: