0

What's the best way to get the csrf token in VueJS?

I don't have any idea to access the token via VueJS. Should it be an ajax call? But, I think it'll be risky, right?

Terry Djony
  • 1,975
  • 4
  • 23
  • 41

1 Answers1

2

You may want to consult your server-side framework's documentation to see how it handles it by default as that may affect what is easiest, but there are multiple solutions.

You could set a cookie to store the CSRF on the server side and fetch that in your Vue application

Alternatively you can put the CSRF in the initial page load. Put some script tags in the header and assign it to a variable there. For instance, if you were using Handlebars, you might do something like this:

<script>
    var token = "{{ token }}";
</script>

Then you can access the token from the variable.

EDIT: Didn't see you were using Slim, and it appears to require multiple values, but the principle is the same. If you're using Twig the syntax is the same and you can set as many values as you need in the same way.

Matthew Daly
  • 9,212
  • 2
  • 42
  • 83