FlaskWTF how to send CSRF token to Vue front-end FlaskWTF how to send CSRF token to Vue front-end flask flask

FlaskWTF how to send CSRF token to Vue front-end


This is a fairly opinionated question with no "right" answer. My preference for SPAs is to do a cookie-to-header token flow, meaning your backend issues a csrf token cookie and your front-end sends it back as a header. This is a fairly prevalent pattern and fetch libraries like axios will automatically find your CSRF token cookie and append it to requests to your backend as a header.

It looks like in Flask-WTF you can generate a csrf token and add it as a cookie yourself:

from flask_wtf.csrf import generate_csrf@app.after_requestdef set_xsrf_cookie(response):    set_cookie('CSRF-TOKEN', generate_csrf())    return response

At this point, you'll want to make sure you see a "CSRF-TOKEN" cookie being set from the server. If so, you're good to move on to the next step, which is sending this token back as a header.

To do so, you can configure a fetch client to always send the same token back as an X-CSRF-TOKEN header, but I personally like the axios fetch client because it automatically does this for you.