我计划每次使用useEffect更改页面时,都会在客户端检查会话有效性。我想知道这是否有可能,或者当我以这种方式实现它时,可能会有什么缺点。
这就是它的样子。
export default function App({ Component, pageProps }) {
useEffect(() => {
//check API to validate session
}, [Component]);
return (
<Component {...pageProps}/>
);
}发布于 2022-01-12 17:29:54
是的,伙计,这是可能的,但是使用NextJs,您将失去服务器端呈现功能,在本例中,我建议您执行类似于重写getServerSideProps函数的操作,并将会话验证添加到其中,因为nextJs端可以访问cookie和会话。
这是你可以做的一个例子:
withSSRAuth.ts (文件)
import { GetServerSideProps, GetServerSidePropsContext, GetServerSidePropsResult } from 'next';
import {
getSession,
} from 'next-auth/client';
import { destroyCookie, parseCookies } from 'nookies';
import { AuthTokenError } from 'services/errors/AuthTokenError';
export function withSSRAuth<P>(fn: GetServerSideProps<P>): GetServerSideProps {
return async (ctx: GetServerSidePropsContext): Promise<GetServerSidePropsResult<P>> => {
const session = await getSession(ctx);
const cookies = parseCookies(ctx);
const { 'uberPlantao.user': savedUser } = cookies;
if (!session && !savedUser) {
return {
redirect: {
destination: '/',
permanent: false,
},
};
}
try {
return await fn(ctx);
} catch (err) {
if (err instanceof AuthTokenError) {
destroyCookie(ctx, 'uberPlantao.user');
destroyCookie(ctx, 'uberPlantao.token');
destroyCookie(ctx, 'uberPlantao.refreshToken');
return {
redirect: {
destination: '/',
permanent: false,
},
};
}
return err;
}
};
}然后将其用作您的getServerSideProps (当您想将会话验证到某个页面时)
页面index.tsx (需要会话验证)
import Image from 'next/image';
import { useRef, useCallback } from 'react';
import { FiUser, FiLock } from 'react-icons/fi';
import { useRouter } from 'next/router';
import { Form } from '@unform/web';
import { FormHandles } from '@unform/core';
import { toast } from 'react-toastify';
import * as Yup from 'yup';
import getValidationErrors from 'utils/getValidationErrors';
import { withSSRAuth } from 'utils/withSSRAuth';
import { Button } from 'components/Atoms/Button';
import { FbButton } from 'components/Atoms/FbButton';
import { Input } from 'components/Atoms/Input';
import { Seo } from 'components/Atoms/Seo';
import { Separator } from 'components/Atoms/Separator';
import {
Container, LogoContainer, FormContainer, ButtonsContainer, Footer,
} from 'styles/pages/index';
import { useAuth } from 'hooks/auth';
type DataFormInfo = {
email: string;
password: string;
}
const Home = (): JSX.Element => {
const formRef = useRef<FormHandles>(null);
const { push } = useRouter();
const { signInWithFacebook, isLoading, defaultSignIn } = useAuth();
const handleFbLogin = async (): Promise<void> => {
signInWithFacebook();
};
const handleLogin = useCallback(
async (data: DataFormInfo) => {
console.log('login');
},
[defaultSignIn, push],
);
return (
<Container>
<Seo title="Home | Uber de plantões" metaDesc="Created by thl dev" />
<LogoContainer>
</LogoContainer>
<FormContainer>
<Form ref={formRef} onSubmit={handleLogin} autoComplete="off">
</Form>
</FormContainer>
<Separator className="sep" type="horizontal" customWidth={40} />
<Footer>
</Footer>
</Container>
);
};
export default Home;
export const getServerSideProps = withSSRAuth(async () => ({
props: {},
}));每次使用withSSRAuth作为getServerSideProps包装器时,都会验证cookie中是否有用户(您也可以使用会话,但在我的例子中,我使用了cookie)
如果没有用户,它将重定向到某个url,您可以选择到目的地。
这种验证会话的方法并不是最好的方法,但它可以防止页面在通过客户端检查是否有用户时闪烁。
https://stackoverflow.com/questions/68207851
复制相似问题