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

zerosAndOnes's avatar

How to make and persist Auth API request to Laravel endpoint in Nuxt and Pinia

Hello developers,

I am new to nuxt/vue and pinia state managent library, and I was wondering if someone has a code sample on how to go about making an api request to a laravel endpoint to register a user, for instance. I have created the API endpoint using laravel and I am using sanctum for token.

I am also using the latest version of Nuxt.

Thanks in advance.

0 likes
3 replies
LaryAI's avatar
Level 58

To make and persist an authentication API request to a Laravel endpoint in Nuxt with Pinia, you'll need to follow these steps:

  1. Set up Laravel Sanctum for API token authentication.
  2. Create a Pinia store in Nuxt to manage the state.
  3. Make an API request from Nuxt to the Laravel endpoint.
  4. Store the received token and user information in the Pinia store.
  5. Persist the authentication state to prevent losing it on page refresh.

Here's a basic example of how you can achieve this:

First, ensure Laravel Sanctum is properly configured for your API. Follow the Sanctum documentation to set it up.

Next, create a Pinia store in Nuxt for authentication:

// store/auth.js
import { defineStore } from 'pinia'
import axios from 'axios'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: null,
  }),
  actions: {
    async registerUser(credentials) {
      try {
        const response = await axios.post('http://your-laravel-app.test/api/register', credentials)
        this.token = response.data.token
        this.user = response.data.user
        // Persist the token in localStorage or cookies
        localStorage.setItem('auth_token', this.token)
      } catch (error) {
        console.error('Registration failed:', error)
      }
    },
    async loginUser(credentials) {
      try {
        const response = await axios.post('http://your-laravel-app.test/api/login', credentials)
        this.token = response.data.token
        this.user = response.data.user
        // Persist the token in localStorage or cookies
        localStorage.setItem('auth_token', this.token)
      } catch (error) {
        console.error('Login failed:', error)
      }
    },
    logoutUser() {
      this.user = null
      this.token = null
      localStorage.removeItem('auth_token')
    },
    loadUserFromStorage() {
      const token = localStorage.getItem('auth_token')
      if (token) {
        this.token = token
        // Optionally, fetch the user data from the API using the token
      }
    }
  }
})

In your Nuxt page or component, you can use this store to register or log in a user:

<template>
  <div>
    <form @submit.prevent="register">
      <!-- Registration form fields -->
      <button type="submit">Register</button>
    </form>
  </div>
</template>

<script>
import { useAuthStore } from '~/store/auth'

export default {
  methods: {
    async register() {
      const credentials = {
        // ...collect your form data
      }
      const authStore = useAuthStore()
      await authStore.registerUser(credentials)
    }
  }
}
</script>

Finally, to persist the authentication state, you can call loadUserFromStorage when the app starts or when the store is initialized:

// store/auth.js
// ...rest of the store

export const useAuthStore = defineStore('auth', {
  // ...state and actions

  // Call this action when the store is initialized
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'auth',
        storage: localStorage,
        paths: ['token', 'user']
      }
    ]
  }
})

Make sure to replace 'http://your-laravel-app.test/api/register' and 'http://your-laravel-app.test/api/login' with your actual Laravel API endpoints.

This example assumes that your Laravel API returns a token and user object upon successful registration or login. Adjust the code as necessary based on your API's response structure. Also, consider using secure storage and handling for the token, such as HttpOnly cookies, to enhance security.

zerosAndOnes's avatar

According to laravel's website, to use sanctum, we have to first make a request to:

/sanctum/csrf-cookie

e.g,

axios.get('/sanctum/csrf-cookie').then(response => {
    // Login...
});

But I don't see that being outlined by the bot. I will try using some of the suggestions, but certain things are not clear on the pinia side. For instance, storing data in localStorage but having a persist object as well. I don't understand why that is needed, if someone else can help answer this. Thanks.

1 like
zerosAndOnes's avatar

I was able to figure this out after I saw a YT video. Thanks a lot!

Please or to participate in this conversation.