otlichnyy
07/03/2022, 12:15 PMrp_st
07/03/2022, 12:17 PMgetServerSideProps and use that to render the page: https://supertokens.com/docs/thirdpartyemailpassword/nextjs/session-verification/in-ssrotlichnyy
07/03/2022, 12:18 PMrp_st
07/03/2022, 12:19 PMotlichnyy
07/03/2022, 12:21 PMts
import backendConfig from 'config/backendConfig';
import dynamic from 'next/dynamic';
import EmailPassword, {
redirectToAuth,
} from 'supertokens-auth-react/recipe/emailpassword';
import { signOut } from 'supertokens-auth-react/recipe/session';
import Supertokens from 'supertokens-node';
import Session from 'supertokens-node/recipe/session';
const EmailPasswordAuthNoSSR = dynamic(
new Promise<typeof EmailPassword.EmailPasswordAuth>((res) => {
res(EmailPassword.EmailPasswordAuth);
}),
{ ssr: false }
);
export async function getServerSideProps(context: any) {
Supertokens.init(backendConfig());
let session;
try {
session = await Session.getSession(context.req, context.res);
} catch (err: any) {
if (err.type === Session.Error.TRY_REFRESH_TOKEN) {
return { props: { fromSupertokens: 'needs-refresh' } };
}
if (err.type === Session.Error.UNAUTHORISED) {
return { props: {} };
}
throw err;
}
return {
props: { userId: session!.getUserId() },
};
}
function ServerRenderProtectedPage({ userId }: { userId: any }) {
async function handleSignout() {
await signOut();
redirectToAuth();
}
return (
<div>
<h1>Server Side rendered Page</h1>
<p>User ID: {userId}</p>
<button onClick={handleSignout}>Logout</button>
</div>
);
}
const Server = ({ userId }: { userId: any }) => {
return (
<>
<p>im ssr-ed</p>
<EmailPasswordAuthNoSSR>
<ServerRenderProtectedPage userId={userId} />
</EmailPasswordAuthNoSSR>
</>
);
};
export default Server;otlichnyy
07/03/2022, 12:22 PM<ServerRenderProtectedPage userId={userId} /> server side rendered???, coz right now its not rendering on serverrp_st
07/03/2022, 12:23 PMEmailPasswordAuthNoSSR which is using dynamic, with SSR false.
You should remove the use of EmailPasswordAuthNoSSR for this page and rely directly on the userId prop returned by getServerSideProps.otlichnyy
07/03/2022, 12:25 PMrp_st
07/03/2022, 12:25 PMotlichnyy
07/03/2022, 12:26 PMotlichnyy
07/03/2022, 12:27 PMdoesSessionExist might work here!rp_st
07/03/2022, 12:29 PMerr.type === Session.Error.UNAUTHORISED statement, in which you are retuning an empty object.
So in this case, the userId prop passed to Server component will be undefined. So you can check that and use that as a way to know if a session exists or nototlichnyy
07/03/2022, 12:29 PMotlichnyy
07/03/2022, 12:32 PM