sidebase / nuxt-auth

Authentication built for Nuxt 3! Easily add authentication via OAuth providers, credentials or Email Magic URLs!
https://auth.sidebase.io
MIT License
1.31k stars 164 forks source link

Explanation of the implications of working with custom middleware #831

Closed pablo-vega-kloeckner-i closed 2 months ago

pablo-vega-kloeckner-i commented 3 months ago

Describe the feature

When using a custom middleware. Do the middleware options inside the page lose their validity?

Custom middleware

// file: ~/middleware/authentication.global.ts

Page configuration

definePageMeta({
  auth: {
    unauthenticatedOnly: true,
    navigateAuthenticatedTo:“/customers”,
  },
});

How would you implement this?

If this is relevant, the documentation could be updated.

Additional information

Provider

Tcrussell436 commented 3 months ago

Do the middleware options inside the page lose their validity?

Yes, for an example just look at their middleware https://github.com/sidebase/nuxt-auth/blob/main/src/runtime/middleware/auth.ts

pablo-vega-kloeckner-i commented 3 months ago

@Tcrussell436 So if I understand correctly if I want to use custom middleware (// file: ~/middleware/authentication.global.ts) I will need to handle the guest mode but myself.

 // file: ~/middleware/authentication.global.ts
export default defineNuxtRouteMiddleware((to) => {
  const { status, signIn } = useAuth()

  // Return immediately if user is already authenticated or the page allows **guess mode**
  if (status.value === 'authenticated' || to?.meta?.auth?.unauthenticatedOnly) {
    return
  }

  return signIn(undefined, { callbackUrl: to.path }) as ReturnType<typeof navigateTo>
})
zoey-kaiser commented 3 months ago

So if I understand correctly if I want to use custom middleware (// file: ~/middleware/authentication.global.ts) I will need to handle the guest mode but myself.

HI @pablo-vega-kloeckner-i 👋

Middleware in Nuxt can "stack" upon each other. If you enable our middleware and then add your own middleware they will both run. You can check the Nuxt docs on how to properly order middleware and when which should run: https://nuxt.com/docs/guide/directory-structure/middleware

If you disable our pre-built middleware, you will need to implement your own, this includes features such as guest-mode. The Page middleware you set will overwrite the settings of the global middleware that you define inside your Nuxt config.

By setting { auth: false } inside a page meta, you completely disable our middleware for that page. I hope this answers a majority of your questions!

zoey-kaiser commented 2 months ago

Closing, as all seems well here 😊