DEV Community

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

Posted on

19

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay