Next.js服务器端重定向会覆盖区域设置



在我的一些页面中,我使用getServerSideProps进行API调用,并在必要时重定向用户。我正在构建的网络应用程序是多语言的,我需要始终向用户显示正确的语言。

主页CCD_ 2使用CCD_。为此,我做了以下事情:

return {
redirect: {
permanent: false,
destination: someLogic ? `${context.locale}/login` : `${context.locale}/profile`,
},
};

现在配置文件和用户页面也使用getServerSideProps来检查是否存在有效会话,并在必要时重定向用户。例如,当用户的会话到期时,他将尝试访问配置文件页面,然后他将被重定向到登录页面。如果我将destination属性设置为/login,则区域设置属性将被覆盖,用户将获得默认语言并重定向到domain/login。如果我将其设置为${context.locale}/login,并且最初调用的页面是domain/fr-FR/profile,则用户将被重定向到domain/fr-FR/fr-FR/login

使用router.pushrouter.replace的客户端重定向工作正常,并返回正确的URL。

据我所知,我无法从getServerSideProps的上下文中获得绝对URL来检查是否已经设置了区域设置,那么我该如何解决这个问题?

我目前正在使用next 10.0.4,这是我的next.config.js:

module.exports = {
i18n: {
locales: ['de-DE', 'en-US', 'fr-FR', 'nl-NL', 'it-IT'],
defaultLocale: 'en-US',
localDetection: true,
}
}

我遇到了同样的问题,并按照以下步骤解决了它:

  • 将上下文传递给getServerSideProps:
export const getServerSideProps = async (context) => {
  • 从上下文中获取区域设置:
const { locale } = context;
  • 使用模板文字将当前区域设置与所需的目标连接起来:
return {
redirect: {
destination: `/${locale}${getLoginPageUrl()}`,
permanent: false,
},
};

这是我警卫的全部代码:

export function withAuthServerSideProps(getServerSidePropsFunc) {
return async (context) => {
const {
req: { cookies },
query: { city },
locale,
} = context;

if (!cookies.userToken) {
return {
redirect: {
destination: `/${locale}${getLoginPageUrl(city ? city : '')}`,
permanent: false,
},
};
}
if (getServerSidePropsFunc) {
return { props: { data: await getServerSidePropsFunc(context) } };
}
return { props: {} };
};
}

这里有一个我如何使用它的例子:

export const getServerSideProps = withAuthServerSideProps(async (context) => {
const res = await ProductsService.fetchOrderDetails({
id: 'b324015f-bf3f-4862-9817-61b954278168',
});

if (!res.data) {
return {
notFound: true,
};
}

return {
props: {
orderDetails: res.data,
},
};
});

请记住,如果您使用此保护,您的道具将在数据中,因此例如,为了让我访问页面中以前代码中的订单详细信息,我必须进行以下操作:

const OrderConfirmed = ({ data }) => (
<OrderConfirmedPageWrapper orderDetails={data?.props?.orderDetails} />
);

我目前正在使用"next": "10.0.6",这是我的next.config.js:

i18n: {
locales: [
'en-kw',
'ar-kw',
'en-sa',
'ar-sa',
'en-qa',
'ar-qa',
'en-bh',
'ar-bh',
'en-ae',
'ar-ae',
'en-gb',
'ar-gb',
'catchAll',
],
defaultLocale: 'catchAll',
},

区域设置被应用了两次,因为您设置的目标路径没有前导/。只需在开头添加一个/就可以解决您的问题。

return {
redirect: {
permanent: false,
destination: someLogic ? `/${context.locale}/login` : `/${context.locale}/profile`
//                        ^                            ^
}
};

最新更新