我的应用程序由 API (nestjs) 和客户端 (nextjs) 组成。
我正在使用 getServerSideProps 来验证用户身份,并在发生错误时重定向到登录站点:
export const getServerSideProps: GetServerSideProps = async (context) => {
try {
// Check whether the user is logged in
await axios.get(
`${process.env.NEXT_PUBLIC_API}/authentication`,
{
withCredentials: true,
// Cookies are attached to the request with context
headers: context.req ? { cookie: context.req.headers?.cookie || '' } : { cookie: '' },
},
);
return {
props: {},
};
} catch (err) {
return {
redirect: {
destination: '/login',
permanent: false,
},
};
}
}; …Run Code Online (Sandbox Code Playgroud)