framework icon indicating copy to clipboard operation
framework copied to clipboard

Component setup runs before router middleware is resolved

Open sangyookm opened this issue 2 years ago • 8 comments

Environment


  • Operating System: Darwin
  • Node Version: v18.12.0
  • Nuxt Version: 3.0.0-rc.13
  • Nitro Version: 0.6.1
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: runtimeConfig, vite, modules, i18n
  • Runtime Modules: @pinia/[email protected], @nuxtjs/[email protected]
  • Build Modules: -

Reproduction

// middleware/auth.global.js
export default defineNuxtRouteMiddleware(async (to)=> {
  if (process.client) return

  const app = useNuxtApp()
  const event = app.ssrContext.event
  const accessToken = getCookie(event, 'accessToken')
  
  // Authenticate if accessToken exists
  // ...

  const { isLoggedIn } = useUserStore()
  const publicPaths = [
    //.. some public paths not needing authentication
  ]
  if (!publicPaths.includes(to.path) && !isLoggedIn) {
    return navigateTo('/login')
  } else if (publicPaths.includes(to.path) && isLoggedIn) {
    return navigateTo('/')
  } 
})

// pages/index.vue
export default defineNuxtComponent({
  async setup() {
    const {data: someData} = await useAsyncData(()=> {
      return $fetch('/api/some_api_auth_required', {
        method: 'get',
        headers: useRequestHeaders(['cookie'])
      })
    })
    return {
      someData
    }
  }
})

Describe the bug

I'm seeing that setup block data fetching is being called before router middleware is resolved.

When I visit '/' without authentication, the page redirects to '/login' like expected.

But, on nuxt server console, I'll see that '/api/some_api_auth_required' was called and failed because accesstoken doesnt exist (not authenticated).

Is this normal behavior? If so, how w

Additional context

No response

Logs

No response

sangyookm avatar Nov 08 '22 14:11 sangyookm