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

Michael Fayez's avatar

nuxt auth

I got this error

AxiosError {message: 'Request failed with status code 419', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
code
: 
"ERR_BAD_REQUEST"
config
: 
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
: 
"Request failed with status code 419"
name
: 
"AxiosError"
request
: 
XMLHttpRequest {requestMethod: 'POST', readyState: 4, timeout: 0, withCredentials: true, onreadystatechange: ƒ, …}
response
: 
{data: {…}, status: 419, statusText: 'unknown status', headers: AxiosHeaders, config: {…}, …}
stack
: 
"AxiosError: Request failed with status code 419\n    at settle (http://localhost:3000/_nuxt/node_modules/.vite/deps/axios.js?v=c5d2ac63:1186:12)\n    at XMLHttpRequest.onloadend (http://localhost:3000/_nuxt/node_modules/.vite/deps/axios.js?v=c5d2ac63:1410:7)"
[[Prototype]]
: 
Error

this is axios :-

import axios from "axios"

export default defineNuxtPlugin((NuxtApp) => {
    axios.defaults.baseURL = 'http://localhost:8000'
    axios.defaults.withCredentials = true;
    axios.defaults.xsrfCookieName = "XSRF-TOKEN";
     axios.defaults.headers.common["Accept"] = "application/json"; // Fix the headers assignment

     axios.interceptors.request.use(async (config) => {
       try {
         const csrfToken = document.cookie.replace(
           /(?:(?:^|.*;\s*)XSRF-TOKEN\s*=\s*([^;]*).*$)|^.*$/,
           ""
         );

         config.headers = config.headers || {};
         config.headers.common = config.headers.common || {};
         config.headers.common["X-CSRF-TOKEN"] = csrfToken;
       } catch (error) {
         console.error("Error setting CSRF token:", error);
       }
       return config;
     });

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

here is register.vue

<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);

        errors.value = error.response ? error.response.data.errors : { general: ['An error occurred.'] };
    }
};

</script>
0 likes
1 reply
LaryAI's avatar
Level 58

The error you're encountering, "Request failed with status code 419," typically indicates a CSRF (Cross-Site Request Forgery) token mismatch error. This can happen when the CSRF token is not set correctly or is missing from the request headers when making a POST request in a Laravel application.

Here's how you can address this issue:

  1. Ensure that your Laravel backend is set up to use CSRF protection and that the XSRF-TOKEN cookie is being set correctly.

  2. In your Nuxt.js application, make sure you are reading the XSRF-TOKEN cookie correctly and attaching it as a header to your Axios requests.

  3. Verify that the withCredentials option is set to true in your Axios configuration to allow sending cookies with cross-origin requests.

Here's a revised version of your Axios plugin configuration that should help resolve the issue:

import axios from "axios";

export default defineNuxtPlugin((NuxtApp) => {
    axios.defaults.baseURL = 'http://localhost:8000';
    axios.defaults.withCredentials = true; // Ensure credentials are sent with requests
    axios.defaults.headers.common["Accept"] = "application/json";

    axios.interceptors.request.use((config) => {
        // Get the CSRF token from the cookie
        const csrfToken = document.cookie
            .split('; ')
            .find(row => row.startsWith('XSRF-TOKEN='))
            ?.split('=')[1];

        if (csrfToken) {
            // Set the CSRF token in the headers
            config.headers['X-CSRF-TOKEN'] = csrfToken;
        }

        return config;
    });

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

Make sure that your Laravel backend is sending the XSRF-TOKEN cookie and that your frontend is able to read it. If you're still encountering issues, you may need to check your Laravel session configuration and ensure that the SESSION_DOMAIN and SANCTUM_STATEFUL_DOMAINS (if you're using Laravel Sanctum) are configured correctly to include your Nuxt.js application's domain.

Additionally, in your register.vue component, ensure that the userStore.getTokens() method is correctly retrieving and storing the CSRF token if necessary.

If you've verified all of the above and the issue persists, you may want to check the Laravel logs for more details on why the CSRF token validation is failing.

Please or to participate in this conversation.