Morgbn / nuxt-csurf

Nuxt Cross-Site Request Forgery (CSRF) Prevention
https://nuxt-csurf.vercel.app
MIT License
81 stars 16 forks source link

Unable to fetch data during app initialization - csrf token mismatch #17

Closed Autraz closed 1 year ago

Autraz commented 1 year ago

CSRF token always mismatch when fetch is called immediatelly at the app load. Look at code below, I just added a await testPost(true) to your playground example.

<template>
  <div>
    <h1>Test CSRF <small>with useCsrfFetch</small></h1>
    <p><small>or test <nuxt-link to="/test-fetch">with $csrfFetch</nuxt-link></small></p>
    <button @click="testPost()">
      POST /test (without csrf header)
    </button>
    <button @click="testPost(true)">
      POST /test (with csrf header)
    </button>
    <button @click="testPost(false, '/nocsrf')">
      POST /nocsrf (without csrf header)
    </button>
    <br>
    <br>
    <pre
      v-if="msg"
      :style="{ color: msgColor }"
    >{{ msg }}</pre>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useCsrfFetch, useFetch } from '#imports'

const msg = ref(null)
const msgColor = ref('green')
const testPost = async (withCsrf, url = '/test') => {
  msg.value = null
  msgColor.value = 'green'
  const fetch = withCsrf ? useCsrfFetch : useFetch
  const { data, error } = await fetch('/api' + url, { method: 'POST' })
  msg.value = data.value || error.value
  if (error.value) { msgColor.value = 'red' }
}

await testPost(true)
</script>

result on page load: image

can this module only be used in client side events? After all, the data retrieval presented in the example can also be triggered on the client side, e.g. when navigating to another page via nuxt-link