0

I have an Angular application and to send analytics data to the server I defined the service that used the navigator.sendBeacon(). I wanted to add X-XSRF-TOKEN into the request header of navigator.sendBeacon(). But as you know, it's not possible, or at least I don't know how to do it. I know I can do it by fetching API but I am curious, is it a better way to do this?

fetch('url', {
  keepalive: true,
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-XSRF-TOKEN': 'sample-token',
  },
  body: JSON.stringify(sample-data),
});
FarbodKain
  • 229
  • 3
  • 15
  • What backend stack are you using? Did you configure it to generate an X-XSRF-TOKEN non-http-only cookie on each webrequest? – Pieterjan Mar 06 '23 at 19:06
  • it's java and I don't understand your second question exactly, I generate XSRF-TOKEN for all requests, but because any request has no token, I supposed it's called outside the HttpModuleClient so I need to manually add X-XSRF-TOKEN for it. – FarbodKain Mar 07 '23 at 07:54
  • 1
    [This is how](https://medium.com/@pieterjandeclippel/asp-net-core-angular-xsrf-62c3833fd1fe#54f1) it's usually done. But that only works for ajax-calls sent through the angular `HttpClient`. Since you're using the `fetch` api, after a similar setup you only need to use javascript to read the `XSRF-TOKEN` from the cookie and use it in your code snippet – Pieterjan Mar 07 '23 at 09:03
  • [This is the .NET (not java) code](https://github.com/MintPlayer/MintPlayer.AspNetCore.XsrfForSpas/blob/master/MintPlayer.AspNetCore.XsrfForSpas/AntiforgeryMiddleware.cs#L27-L28) that generates the xsrf-token and appends the `X-XSRF-TOKEN` response header. You need something similar for your java backend. Then simply read this cookie and send the token in your beacon – Pieterjan Mar 07 '23 at 09:09
  • I appreciate your help, I already config my angular app. I need to send data to external services, and because I don't want that request to block another request I used sendBeacon(). I need to find a way to add x-xsrf-token to the request header. manually for this request. – FarbodKain Mar 10 '23 at 08:38

0 Answers0