[英]Nuxt3 SSR server/client middleware causing the protected page to render unintentionally
I'm developing a Nuxt SSR app with a simple authentication.我正在开发一个带有简单身份验证的 Nuxt SSR 应用程序。
I have auth middleware
to guard all login required routes.我有auth middleware
来保护所有登录所需的路由。
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该中间件检查存储中的浏览器 cookie,因此它需要在客户端运行
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.据我了解,通常 SSR 中间件首先在服务器端运行,然后在客户端运行。
The problem is, when I apply this auth miidleware to gaurd a login required page问题是,当我应用此 auth miidleware 来保护登录所需页面时
<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.你可以看到它在行动。
Has anyone run into this problem before?有没有人遇到过这个问题? Any solution would be really appreiated.任何解决方案都会受到赞赏。 My requirement is to use SSR for this app.我的要求是为此应用程序使用 SSR。
Plus, another small problem.另外,还有一个小问题。 when running SSR and you refresh the page, there's some style fickering.运行 SSR 并刷新页面时,会出现一些样式变化。 I'm not sure why.我不确定为什么。 I'm using this template https://github.com/sfxcode/nuxt3-primevue-starter我正在使用这个模板https://github.com/sfxcode/nuxt3-primevue-starter
I've been looking for a solution for several days already @_@几天来我一直在寻找解决方案@_@
In general, it is not necessary to use "SSR" for protected pages, because only public pages need to be indexed for search engines.一般来说,受保护的页面不需要使用“SSR”,因为只有公共页面需要为搜索引擎编制索引。 In SSR mode, you have access to the data stored in cookies.在 SSR 模式下,您可以访问存储在 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.要获得它们,最方便的是使用与 cookies 一起使用的特殊库,以免在您处于 SRR 或 CSR 时规定所有可能的情况。 For Nuxt 2, I use the cookie-universal-nuxt library.对于 Nuxt 2,我使用 cookie-universal-nuxt 库。 Try to make sure that the DOM tree does not differ on the server and the client, otherwise errors may occur.尽量确保 DOM 树在服务器和客户端上没有差异,否则可能会出现错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.