在Next.js中由于缺乏会话而重定向时如何显示toast通知?



例如,假设我有一个名为internal的页面。有:

的TSX
export const getServerSideProps: GetServerSideProps = async (ctx) => {
const session = await getSession(ctx);
if (!session) {
// TODO: Add a toast notification explaining the redirect. Ideally, the desired destination should be remembered and should be redirected to after login.
return {
redirect: {
destination: '/',
permanent: false,
},
};
}
const props = ...
return { props };
};

如果访问者在/internal上浏览这个页面,他们会被跳转到我的登录页面,没有任何解释。

相反,我希望我的登录页面在屏幕顶部显示一个toast通知,说明他们试图访问的页面需要登录,并且一旦他们登录,他们将返回到该页面。

我计划在登录页面上使用像https://github.com/fkhadra/react-toastify这样的库,但还没有能够弄清楚如何/在哪里从访问者刚刚被重定向的会话中读取。

理想情况下,启动重定向的每个页面(如/internal)都可以指定自己的自定义消息(例如保存到"flash变量"在会话中),在toast中显示登录页面。

根据上面的评论尝试回答。

而不是使用重定向,它可能是更好的使用context和设置一个新的头,做一个context.res.redirect,现在包含新的头flashVariable(从Laravel借用)从我之前的评论-内置的redirect似乎没有能力设置这些值。

export const getServerSideProps: GetServerSideProps = async (ctx) => {
const session = await getSession(ctx);
if (!session) {
ctx.res.setHeader("yourFlashVariable", "yourFlashValue");
ctx.res.redirect('/')
}
const props = ...
return { props };
};

在您的/路由中,您可以查找FlashVariable并调用toast库。

最新更新