Example Page
Inject Headers
When making a request, you will often send something in the header. For example, sending a CSRF token, authorization, cache-control, etc. in Briz.js, all of these can be injected into the z:before-request event. The way it works is “when the request is about to take place, first add the header written in the z:before-request event, then send it to the endpoint”. Below we will give an example with a CSRF token.
Example
<!-- First create a csrf_token on the server, then put it in the meta tag inside the head (i use astro SSR) --><meta name="csrf_token" content={`${csrf_token}`} /><form data-ajax data-swap="result" action="/partials/headers" method="post"> <input type="text" name="name" required /> <button type="submit">Submit</button></form>The developer must put the token from the server in the meta tag inside <head>, then retrieve it and insert it into the HTTP header via an event like the one below.
document.addeEventListener("z:before-request", (event) => { const request = event.detail.request if(!request) return
if(request.options.method === "POST") { //grab csrf_token from meta tag then use it const csrf_token = document.querySelector("meta[name='csrf_token']")?.getAttribute("content")
//inject headers request.options.headers = { ...(request.options.headers || {}), "x-csrf-token": csrf_token } }})Try pressing the submit button. The system will make a request to /partials/headers with a csrf_token in the HTTP header. Don’t believe me? Open Chrome DevTools, go to the Network tab, and look at the headers. You’ll see a csrf_token there. just write it once, it will add the csrf token to all requests with the POST method
Demo
Go back