I'm learning to use Next Auth and I'm following https://next-auth.js.org/tutorials/securing-pages-and-api-routes#server-side.
I expected since getServerSideProps()
runs on the server side only, that the return
for unauthorized would only show "ACCESS GRANTED!!! ..." but I'm able to search the source code in the browser and find the hash secret I made.
I had some issues so I altered the example code; notably I included a useState
for running on server only substituting the if type === "undefined
method.
pages/protected.js
import { getServerSession } from "next-auth/next"
import { authOptions } from "./api/auth/[...nextauth]"
import { useSession } from "next-auth/react"
import { useEffect, useState } from "react"
import { Typography } from "@mui/material"
import { GetServerSidePropsContext } from "next"
export async function getServerSideProps(context: GetServerSidePropsContext) {
return {
props: {
session: await getServerSession(context.req, context.res, authOptions),
},
}
}
export default function Profile() {
const { data: session } = useSession()
const [isClient, setIsClient] = useState<boolean>(false)
// Run on server only
useEffect(() => {
setIsClient(true)
}, [])
if (isClient && session) {
return (
<>
<Typography>
ACCESS GRANTED!!! SECRET: 11c6c096-f677-4432-b7ca-2d1216df73a3
</Typography>
</>
)
}
return <Typography>NO ACCESS</Typography>
}
Is there something I'm not seeing or not understanding here? I'm able to use the authentication properly and see my session.
I think I misunderstood the way getServerSideProps()
works.
According to https://nextjs.org/docs/pages/api-reference/functions/get-server-side-props, nowhere does it say that the "whole" page is serverside only.
I was confused by "Next.js will pre-render this page on each request" and interpreted this as the component (in this case Profile()
) contents will re-render on each request.
But for sure the contents of the getServerSideProps()
function will be serverside.