How do I store my CSRF token in my frontend nextjs headers. I store my jwt token in cookie

I'm creating a website with flask and nextjs and authenticating with jwt and storing it in cookie. In my main page, I set my CSRFToken in my header in my nextjs (although I created a route in flask that sends CSRFToken and nextjs fetches it). It works on insomnia, but doesn't work on my browser. It keeps giving me a "missing cookie token" error. How do I fix it

In my nextjs, my headers is const res = await fetch('http: localhost:8080/api', { method: 'GET', headers: { 'X-CSRFTOKEN': fetch('http://localhost:8080/get-csrf-token')} }) I was expecting to fetch json files in /API route

Upvotes: 1

Views: 197

Answers (1)

yusufie
yusufie

Reputation: 193

You need to await the CSRF token first. Do this instead:

const csrfResponse = await fetch('http://localhost:8080/get-csrf-token');
const csrfToken = await csrfResponse.text(); // or .json()

const res = await fetch('http://localhost:8080/api', {
 method: 'GET',
 credentials: 'include',
 headers: {
  'X-CSRFTOKEN': csrfToken
  }
});

Upvotes: 0

Related Questions