Auth0 SDK for Nuxt 3

Hello! I haven’t tested this solution thoroughly, but this is the approach I took to set it up in my nuxt app

in plugins/auth0.ts I added auth0 to the vue app:

import { createAuth0 } from "@auth0/auth0-vue";

export default defineNuxtPlugin((nuxtApp) => {
  const runtimeConfig = useRuntimeConfig()

  const auth0 = createAuth0({
    domain: runtimeConfig.public.auth0url,
    clientId: runtimeConfig.public.auth0client,
    ...otherOptions,
  });

  if (process.client)
    nuxtApp.vueApp.use(auth0)
})

then added the auth guard to a route middleware as follows:

import { createAuthGuard } from "@auth0/auth0-vue";

export default defineNuxtRouteMiddleware(async(to, from) => {
  if (!isAuthenticated()) {
    return await createAuthGuard()(to); 
  }
})

in my users’ pinia store, I added useAuth0 composable and exported states I needed:

import { defineStore } from "pinia";
import { useAuth0 } from "@auth0/auth0-vue";

export const useUserStore = defineStore('user', () => {
  const {
    isAuthenticated,
    logout: authLogout,
    loginWithRedirect,
    error,
    user: userProfile,
  } = useAuth0();
  const userId = computed(() => userProfile.value?.sub);

  async function logout() {
    await authLogout({
      logoutParams: { returnTo: window?.location.origin }
    });
  }

  return {
    isAuthenticated,
    userProfile,
    userId,
    error,

    logout,
    login: async () => {
      await loginWithRedirect()
    },
  };
});

I used the users’ store across the app, and navigation guard seems to be working based on the authentication state.

I hope this helps!

1 Like