Nuxt3 SSR server/client middleware causing the protected page to render unintentionally

Viewed 15

I'm developing a Nuxt SSR app with a simple authentication.

I have auth middleware to guard all login required routes.

export default defineNuxtRouteMiddleware(async (to, from) => {
  if (process.client) {
    const authStore = useAuthStore()

    if (!authStore.check) {
      authStore.returnUrl = to.fullPath

      useRouter().push('/admin/login')
    }
  }
})

This middleware checks browser cookie in store, hence it needs to be run on the client side

export const useAuthStore = defineStore('auth', () => {
  const token = ref(useStorage('token', null))
  const check = computed(() => token.value !== undefined)
  ....

From my understanding, normally the SSR middleware runs on the server side first and then the client side.

The problem is, when I apply this auth miidleware to gaurd a login required page

<script setup lang="ts">
definePageMeta({
  middleware: ['admin-auth'],
  // or middleware: 'auth'
})
</script>

<template>
  <div class="flex justify-center items-center h-screen p-3">admin 1</div>
</template>

The middleware will run on the sever side first causing the page to render unintentionally, and then trigger the client side with the logic, and it will redirect back to login page. This is very ulgy. You can see it in action.

Screen-Recording-2565-09-14-at-10 34 25

Has anyone run into this problem before? Any solution would be really appreiated. My requirement is to use SSR for this app.


Plus, another small problem. when running SSR and you refresh the page, there's some style fickering. I'm not sure why. I'm using this template https://github.com/sfxcode/nuxt3-primevue-starter

Screen-Recording-2565-09-14-at-10 27 40


I've been looking for a solution for several days already @_@

1 Answers

In general, it is not necessary to use "SSR" for protected pages, because only public pages need to be indexed for search engines. In SSR mode, you have access to the data stored in cookies. To get them, it is most convenient to use special libraries for working with cookies, so as not to prescribe all possible cases when you are either in SRR or CSR. For Nuxt 2, I use the cookie-universal-nuxt library. Try to make sure that the DOM tree does not differ on the server and the client, otherwise errors may occur.

Related