Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Michael Fayez's avatar

Where to find my CSRF Token ?

Here is my Axios.js code

import axios from "axios"

export default defineNuxtPlugin((NuxtApp) => {
    axios.defaults.baseURL = 'http://localhost:8000'
    axios.defaults.withCredentials = true;
axios.interceptors.request.use((config) => {
  const csrfToken = "X-CSRF-TOKEN"; // Replace with the actual CSRF token from your application
  config.headers.common["X-CSRF-TOKEN"] = csrfToken;
  return config;
});

    return {
        provide: { 
            axios: axios
        },
    }
})

here my register :-

<template>
    <AuthLayout>
        <div class="mt-10">
            <h1 class="lg:text-5xl text-3xl text-center font-extrabold">
                Create your account
            </h1>

            <form 
                class="mt-12" 
                @submit.prevent="register()"
            >
                <div>
                    <TextInput 
                        placeholder="Username"
                        v-model:input="name"
                        inputType="text"
                        :error="errors && errors.name ? errors.name[0] : ''"
                    />
                </div>

                <div class="mt-4">
                    <TextInput 
                        placeholder="Email: [email protected]"
                        v-model:input="email"
                        inputType="email"
                        :error="errors && errors.email ? errors.email[0] : ''"
                    />
                </div>

                <div class="mt-4">
                    <TextInput 
                        placeholder="Password"
                        v-model:input="password"
                        inputType="password"
                        :error="errors && errors.password ? errors.password[0] : ''"
                    />
                </div>

                <div class="mt-4">
                    <TextInput 
                        placeholder="Confirm Password"
                        v-model:input="confirmPassword"
                        inputType="password"
                    />
                </div>

                <div class="mt-10">
                    <button
                        type="submit"
                        class="rounded-full w-full p-3 font-bold"
                        :disabled="(!name || !email || !password || !confirmPassword)"
                        :class="
                            (name && email && password && confirmPassword) 
                                ? 'bg-[#8228D9] hover:bg-[#6c21b3] text-white' 
                                : 'bg-[#EFF0EB] text-[#A7AAA2]'
                        "
                    >
                        Create account
                    </button>
                </div>
            </form>

            <div class="text-[14px] text-center pt-12">
                Already have an account?
                <NuxtLink 
                    to="/"
                    class="text-[#8228D9] underline"
                >
                    Log in
                </NuxtLink>
            </div>
        </div>
    </AuthLayout>
</template>

<script setup>
import AuthLayout from '~/layouts/AuthLayout.vue';

import { useUserStore } from '~~/stores/user';
const userStore = useUserStore()

const router = useRouter()

definePageMeta({ middleware: 'is-logged-in' })

let name = ref(null)
let email = ref(null)
let password = ref(null)
let confirmPassword = ref(null)
let errors = ref(null)


const register = async () => {
    errors.value = null;

    try {
        await userStore.getTokens();
        await userStore.register(
            name.value, 
            email.value, 
            password.value, 
            confirmPassword.value
        );
        await userStore.getUser();
        router.push('/admin');
    } catch (error) {
        console.log(error);

        // Check if error.response is defined before accessing its properties
        errors.value = error.response ? error.response.data.errors : { general: ['An error occurred.'] };
    }
};

</script>

I got the error

TypeError: Cannot set properties of undefined (setting 'X-CSRF-TOKEN')
    at axios.js:8:1
    at async Proxy.getTokens (user.js?t=1702143685132:65:7)
    at async Proxy.register (register.vue:114:1)
0 likes
1 reply
LaryAI's avatar
Level 58

It looks like you're trying to set the CSRF token in your Axios interceptor, but you're not actually retrieving the token from anywhere. In a typical Laravel application, the CSRF token is stored in a meta tag within your HTML's head section. You need to retrieve this token and then set it in your Axios requests.

Here's how you can modify your code to include the CSRF token:

First, ensure that your Laravel layout includes the CSRF token meta tag. In your main blade layout file (usually resources/views/layouts/app.blade.php), add the following line inside the <head> section:

<meta name="csrf-token" content="{{ csrf_token() }}">

Next, in your axios.js file, you can retrieve the CSRF token from the meta tag and set it in the Axios interceptor:

import axios from "axios"

export default defineNuxtPlugin((NuxtApp) => {
    axios.defaults.baseURL = 'http://localhost:8000'
    axios.defaults.withCredentials = true;

    axios.interceptors.request.use((config) => {
        // Retrieve the CSRF token from the meta tag
        const csrfToken = document.head.querySelector('meta[name="csrf-token"]');

        if (csrfToken) {
            config.headers.common["X-CSRF-TOKEN"] = csrfToken.content;
        } else {
            console.error('CSRF token not found');
        }

        return config;
    });

    return {
        provide: { 
            axios: axios
        },
    }
})

This code snippet retrieves the CSRF token from the meta tag and sets it in the Axios request headers. If the token is not found, it logs an error to the console.

Make sure that your Nuxt.js application is correctly injecting the CSRF token from your backend into the page where your Nuxt.js app is mounted. If you're using SSR (Server-Side Rendering) with Nuxt.js, you might need to pass the CSRF token from your Laravel backend to your Nuxt.js frontend through props or some other mechanism.

If you're using Laravel as an API backend and Nuxt.js for the frontend, and they are on different domains, you might need to configure CORS and CSRF settings appropriately on the Laravel side to ensure that the CSRF token is accepted from the Nuxt.js domain.

Please or to participate in this conversation.