Blitz is now in beta! 🎉 1.0 expected this April
Back to Documentation Menu

Redirects

Topics

Jump to a Topic

On the Client

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 */
}

On the Server

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: {}}
}

Idea for improving this page? Edit it on Github.