DEV Community

Cover image for Nuxt 3 authentication with pinia
Kelvin Chidothi
Kelvin Chidothi

Posted on

18

Nuxt 3 authentication with pinia

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',
  ],
})
Enter fullscreen mode Exit fullscreen mode

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,
})
Enter fullscreen mode Exit fullscreen mode

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.

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay