I'm using nextjs implementation with supertokens, ...
# support-questions
o
I'm using nextjs implementation with supertokens, it's working fine. But do supertokens support SSR with protected page. Does anyone have SSR implementation ??? PS: source code is exactly same as official nextjs implementation
r
You can do session verification in
getServerSideProps
and use that to render the page: https://supertokens.com/docs/thirdpartyemailpassword/nextjs/session-verification/in-ssr
o
well im using email password only
o
Copy code
ts
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;
my question is how can i make
<ServerRenderProtectedPage userId={userId} />
server side rendered???, coz right now its not rendering on server
r
That's cause you are wrapping it with
EmailPasswordAuthNoSSR
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
.
o
alright it worked!
r
Awesome
o
but now my page becomes public
doesSessionExist
might work here!
r
So if a user is not logged in, it will come in the
err.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 not
o
alright!
Awesome, I'll try it, thanks man!
2 Views