Skip to content
This repository has been archived by the owner on Aug 5, 2024. It is now read-only.

dystcz/nuxt-sanctum-auth

Repository files navigation

Nuxt Sanctum Auth

Notice of Deprecation

This package is no longer being developed or maintained. We recommend using the more up-to-date and actively maintained package nuxt-auth-sanctum instead. Thank you for your understanding.

npm version

This is a simple package for integrating Laravel Sanctum auth with Nuxt3. This package is in developement and for now works only in SPA or Hybrid mode. No full SSR support, yet.

Installation

yarn add nuxt-sanctum-auth
# or
npm i nuxt-sanctum-auth

Import the module into the nuxt.config.[js,ts] and disable ssr. Or alternatively disable ssr via routeRules, only for pages where auth or guest middlewares are needed. Typically account section and login page.

export default defineNuxtConfig({
  ssr: false,
  // or
  routeRules: {
    '/account/**': { ssr: false },
    '/auth/**': { ssr: false }
  },

  modules: [
    'nuxt-sanctum-auth'
    // ...
  ]
})

You can also define options as below (defaults in example):

export default defineNuxtConfig({
  // ...
  modules: [
    'nuxt-sanctum-auth'
    // ...
  ],
  nuxtSanctumAuth: {
    token: false, // set true to use jwt-token auth instead of cookie. default is false
    baseUrl: 'http://localhost:8000',
    endpoints: {
      csrf: '/sanctum/csrf-cookie',
      login: '/login',
      logout: '/logout',
      user: '/user'
    },
    csrf: {
      headerKey: 'X-XSRF-TOKEN',
      cookieKey: 'XSRF-TOKEN',
      tokenCookieKey: 'nuxt-sanctum-auth-token'
    },
    redirects: {
      home: '/account',
      login: '/auth/login',
      logout: '/'
    }
  }
})

Usage

Login

Package provides you with $sanctumAuth plugin, which contains login and logout methods.

When you log in using the module, it automatically redirects you to the home route as defined in the configuration. However, you can also pass a callback function as the second parameter, which will receive the response data as an argument. This can be useful, for example, if you want to fetch additional user data before redirecting them to the application. Just keep in mind that you'll need to handle the redirection manually.

<script setup>
const { $sanctumAuth } = useNuxtApp()
const router = useRouter()
const errors = ref([])

async function login() {
  try {
    await $sanctumAuth.login(
      {
        email: 'email@example.com',
        password: 'supersecretpassword'
      },
      // optional callback function
      (data) => {
        console.log(data)
        router.push('/account')
      }
    )
  } catch (e) {
    // your error handling
    errors.value = e.errors
  }
}
</script>

Logout

When you log out, the module will automatically redirect you to the logout route as defined in the configuration. However, you can also choose to pass a callback function to handle the redirect yourself. The callback function will receive the response data from the logout request as an argument. Please note that all session data will be deleted by the time the callback is executed.

<script setup>
const { $sanctumAuth } = useNuxtApp()
const router = useRouter()

const logout = async () => {
  await $sanctumAuth.logout(
    // optional callback function
    (data) => {
      console.log(data)
      router.push('/')
    }
  )
}
</script>

Accessing user

The module creates a useAuth() composable that utilizes useState('auth') in the background. You can use it to get access to a user.

<script setup>
const { user, loggedIn } = useAuth() // or useState('auth').value
</script>

<template>
  <div>
    Is user logged in?
    <span>{{ loggedIn ? 'yes' : 'no' }}</span>
  </div>
  <div v-if="loggedIn">
    What is users name?
    <span>{{ user.name }}</span>
  </div>
</template>

Middleware

Package automatically provides two middlewares for you to use: auth and guest. If you are using routeRules make sure to set ssr: false for all pages that will be using those middlewares. Please note that those middlewares are not global and are needed to be included on every protected page. Global middlewares are not possible for now, beacuse of avaliability of hybrid mode.

Pages available only when not logged in

<script setup>
definePageMeta({
  middleware: 'guest'
})
</script>

Pages available only when logged in

<script setup>
definePageMeta({
  middleware: 'auth'
})
</script>

Using JWT-token auth instead of cookie

If you want to use Laravel Sanctum with JWT token authentication method, set the token property to true in the module configuration.

nuxtSanctumAuth: {
  token: true
  // other properties
}

Your Laravel backend should respond on the login endpoint with a json containing property token:

{
  "token": "1|p1tEPICErFs9TpGKjfkz5QcWDi5M4YqJpVLGUwqM"
}

Once logged in, the token will be saved in a cookie.

If you need to access the token, use property of useAuth()

<script setup>
const { token } = useAuth()
</script>

<template>
  <div>
    What is auth jwt token?
    <span>{{ token }}</span>
  </div>
</template>

Data fetching

In guarded pages, you will have to use special fetching method inside useAsyncData. This methods is responsible for carrying the XSRF or JWT auth token.

<script setup>
const { $apiFetch } = useNuxtApp()
const { data: posts } = await useAsyncData('posts', () => $apiFetch(`posts`))
</script>

Getting user info in pages/components without middleware

You absolutely can use user information on all pages, even on those that are not guarded by auth midleware. Only downside is that you have to handle potential empty states your self. Typically on ssr pages, because user info is accessable only on client.

<script setup>
const { $sanctumAuth } = useNuxtApp()
const loading = ref(true)
const auth = useAuth() // return auth state

onMounted(async () => {
  await $sanctumAuth.getUser() // fetch and set user data
  loading.value = false
})
</script>

<template>
  <div v-if="loading">Loading...</div>
  <div v-else>
    <NuxtLink to="/auth/login" v-if="!auth.loggedIn"> Login </NuxtLink>
    <NuxtLink to="/account" v-else> My Account </NuxtLink>
  </div>
</template>

Development

  • Run npm run dev:prepare to generate type stubs.
  • Use npm run dev to start playground in development mode.