A while ago, l wrote a post on Authenticating a Nuxt 2 application with a Laravel Sanctum API. As much as l like Nuxt.js because of it's cool features like middlewares, plugins, routing, SSR, Nuxt 3 has issues with authentication. Here are some of the reasons:
Some packages have been removed in Nuxt 3 i.e. nuxt-auth
No auth scaffolding
Default configurations for axios, auth have been depreciated in nuxt.config.ts
To write a good authentication logic in Nuxt 3, you have to come up with your own logic in Store, Middlewares (for routing).
I tried sidebase package @sidebase/nuxt-auth
which is a good package but requires more customizations. Later l switched to pinia as documented here:
This method work really well, kudos, but there's a problem again with persistence of state.
To achive this, install the following package:
yarn add -D @pinia-plugin-persistedstate/nuxt
or
npm i -D @pinia-plugin-persistedstate/nuxt
Once this is installed at it under your modules array in nuxt.config.js
export default defineNuxtConfig({
modules: [
'@pinia/nuxt',
'@pinia-plugin-persistedstate/nuxt',
],
})
Finally add a persist prop under your defined store like this:
// ~/store/auth.ts
import { defineStore } from 'pinia'
export const useStore = defineStore('auth', {
state: () => {
return {
authenticated: 'true',
}
},
persist: true,
})
This will automatically instruct pinia to persist any data within it's store attribute. Pinia does this by either using a cookie or local storage, the choice is yours. Reference to this documentation for more global options for pinia persistence.
Top comments (0)