One common use case is conditionally redirecting a user to a different page based on their session data. Here's how you can do that:
import {useRouter, useSession} from "blitz"
const LoginPage: BlitzPage = () => {
const router = useRouter()
const session = useSession()
useEffect(() => {
if (session.userId) {
router.push("/home")
}
})
return /* stuff */
}
If you don't want the "flash of invalid content" that you get with client
side redirects, you can use
getServerSideProps
to conditionally redirect
from the server. Here's how you can do that:
import {getSession} from "blitz"
export const getServerSideProps = async ({req, res}) => {
const session = await getSession(req, res)
if (!session.userId) {
return {
redirect: {
destination: "/login",
permanent: false,
},
}
}
return {props: {}}
}