Nuxt3 SSR server/client middleware causes protected page to render unexpectedly
P粉811349112
2023-08-28 22:36:09
<p>I am developing a Nuxt SSR application with simple authentication. </p>
<p>I have <code>auth middleware</code> to secure all routes required for login. </p>
<pre class="brush:php;toolbar:false;">export default defineNuxtRouteMiddleware(async (to, from) => {
if (process.client) {
const authStore = useAuthStore()
if (!authStore.check) {
authStore.returnUrl = to.fullPath
useRouter().push('/admin/login')
}
}
})</pre>
<p>This middleware checks for stored browser cookies and therefore needs to be run on the client</p>
<pre class="brush:php;toolbar:false;">export const useAuthStore = defineStore('auth', () => {
const token = ref(useStorage('token', null))
const check = computed(() => token.value !== undefined)
....</pre>
<p>As far as I know, SSR middleware usually runs on the server side first and then on the client side. </p>
<p>The problem is when I apply this authentication miidleware to protect pages that require login</p>
<pre class="brush:php;toolbar:false;"><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></pre>
<p>The middleware will first run on the server side, causing the page to render unintentionally, and then trigger the client with logic and redirect it back to the login page. This is very ugly. You can see it in action. </p>
<p>Has anyone encountered this problem? Any solution would be very appreciated. My requirement is to use SSR for this application. </p>
<hr />
<p>Also, there is a small problem. When running SSR and refreshing the page, there is some style flickering. I do not know why. I'm using this template https://github.com/sfxcode/nuxt3-primevue-starter</p>
<hr />
<p>I have been looking for a solution for several days@_@</p>
Generally, there is no need to use "SSR" for protected pages, because only public pages need to be indexed by search engines. In SSR mode you can access data stored in cookies. To obtain them, it is most convenient to use a special library to handle cookies, so that not all possible cases are specified in the SRR or CSR. For Nuxt 2, I use the cookie-universal-nuxt library. Try to ensure that the server and client DOM trees are not different, otherwise errors may occur.