atinux / nuxt-auth-utils

Add Authentication to Nuxt applications with secured & sealed cookies sessions.
MIT License
973 stars 91 forks source link

How to redirect a signed-in user during app startup? #248

Closed julianfox closed 1 month ago

julianfox commented 1 month ago

Hello, I'm having trouble figuring out how to redirect signed-in users right when the app starts.

My first attempt was to add middleware to my landing page ("/"):

export default defineNuxtRouteMiddleware((to, from) => {
  const { loggedIn } = useUserSession()

  if (loggedIn.value) {
    return navigateTo(`/cards`)
  }
})

This works perfectly in my local environment, but in production, the redirection doesn't happen, even though /api/_auth/session returns a 200 status.

I then tried a different approach:

export default defineNuxtRouteMiddleware(async (to, from) => {
  const { loggedIn, fetch } = useUserSession()

  await fetch()

  if (loggedIn.value) {
    return navigateTo(`/cards`)
  }
})

This works, but there's a 2-3 second delay before the user is redirected. The landing page is rendered first, and then the user is redirected a few seconds later. It's better, but not ideal.

I also have a plugin that hooks into fetch on the server:

export default defineNitroPlugin(() => {
  sessionHooks.hook('fetch', async (session, event) => {
    const user = session.user

    if (!user) {
      return
    }

    const userDoc = await UserSchema.findOne({ _id: user._id }, 'premium').lean()

    if (!userDoc) {
      return
    }

    session.user.premium = userDoc.premium

    return session
  })
})

However, even when I remove this plugin, the problem persists.

Is there another solution to handle this more smoothly? Am I doing something wrong?

atinux commented 1 month ago

It works perfectly when tested both locally & in production, see https://github.com/Atinux/nuxt-auth-utils/blob/main/playground/pages/secret.vue

how do you deploy your project in production? Do you have SSR disabled?

julianfox commented 1 month ago

Thanks @atinux, I think I've found the issue:

routeRules: {
    '/': { prerender: true },
  },

I will test, but if I understand it right, prerender by definition do not use SSR?

julianfox commented 1 month ago

Problem fixed; it was indeed due to my route rules configuration.