简体   繁体   English

如何在 Next.js 中使用带有道具的`getServerSideProps`进行重定向?

[英]How to redirect using `getServerSideProps` with props in Next.js?

After a user signs in, I use router.push() to redirect the user to their profile page.用户登录后,我使用router.push()将用户重定向到他们的个人资料页面。 I am using getServerSideProps() for authentication right now.我现在正在使用getServerSideProps()进行身份验证。 When the redirect happens, the props don't seem to be fetched and I have to refresh the browser myself to call gSSR.当重定向发生时,似乎没有获取道具,我必须自己刷新浏览器才能调用 gSSR。 Is this behavior normal or is there a way to fix it?这种行为是正常的还是有办法解决它?

Demonstration - Updated演示 - 更新

login.js登录.js

import {useRouter} from 'next/router';

export default function Login({user}) {
  const router = useRouter();

  // invoked on submission
  async function submitLoginForm(email, password) {
    const user = await signIn(email, password)
    const username = await getUsernameFromDB(user);
    router.push("/" + username);
  }

  return ( ... );
}

export async function getServerSideProps({req}) {
  const user = await getUserFromCookie(req);
  if(user === null) {
    return {
      props: {}
    }
  }
  return {
    redirect: {
      destination: `/${user.username}`,
      permanent: false
    }
  }
}

[username].js [用户名].js

export default function Profile({user, isUser}) {
  // Use isUser to render different interface.
  return ( ... );
}

export async function getServerSideProps({params, req}) {
  // The username of the path.
  const profileUsername = params.username
  // Current user.
  const user = await getUserFromCookie(req);
  ...
  if(user !== null) {
    return {
      props: { 
        user: user, 
        isUser: user !== null && profileUsername === user.username
      }
    }
  }
  return {
    notFound: true
  }
}

The cookie is set in the _app.js using the Supabase auth sdk. cookie 使用 Supabase auth sdk 在_app.js中设置。

function MyApp({Component, pageProps}) {
  supabase.auth.onAuthStateChange( ( event, session ) => {
    fetch( "/api/auth", {
      method: "POST",
      headers: new Headers( { "Content-Type": "application/json" } ),
      credentials: "same-origin",
      body: JSON.stringify( { event, session } ),
    } );
  } );

  return (
    <Component {...pageProps} />
  );
}

I would recommend that you update your _app.js like that:我建议您像这样更新您的_app.js

import { useEffect } from 'react';

function MyApp({ Component, pageProps }) {
  
  // make sure to run this code only once per application lifetime
  useEffect(() => {
    // might return an unsubscribe handler
    return supabase.auth.onAuthStateChange(( event, session ) => {
      fetch( "/api/auth", {
        method: "POST",
        headers: new Headers( { "Content-Type": "application/json" } ),
        credentials: "same-origin",
        body: JSON.stringify( { event, session } ),
      });
    });
  }, []);
  

  return <Component {...pageProps} />;
}

Also, please make clear what is happening.另外,请弄清楚发生了什么。 Eg my current expectation:例如我目前的期望:

  • Not authenticated user opens the "/login" page未通过身份验证的用户打开“/login”页面
  • He does some login against a backend, that sets a cookie value with user information他对后端进行了一些登录,该后端使用用户信息设置了 cookie 值
  • Then router.push("/" + username);然后router.push("/" + username); is called叫做
  • But the problem now: On page "/foo" he sees now the Not-Found page instead of the user profile但现在的问题是:在“/foo”页面上,他现在看到的是 Not-Found 页面而不是用户配置文件
    • Only after page reload, you see the profile page correctly只有在页面重新加载后,您才能正确看到个人资料页面

If the above is correct, then it is possible the following line is not correctly awaiting the cookie to be persisted before the navigation happens:如果以上是正确的,那么在导航发生之前,以下行可能没有正确地等待 cookie 被持久化:

const user = await signIn(email, password)

It could be that some internal promise is not correctly chained/awaited.可能是某些内部 promise 未正确链接/等待。

As an recommendation, I would log to the console the current cookie value before calling the router.push to see if the cookie was already saved.作为建议,我会在调用router.push之前将当前 cookie 值记录到控制台,以查看 cookie 是否已保存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM