Production grade Next.js

Protecting Pages

Lock down

Now that we have users and jwts, we can lock down access to our app at ./pages/app/[[...id]].tsx. This is an optional catch all route which means its inclusive an also matches /app. A user should be signed in to access this route, lets make it so.

First, lets get the session server side with getServerSideProps

./pages/app/[[...id]].tsx
export async function getServerSideProps(context) {
  const session: { user: UserSession } = await getSession(context)
  return {
      props: {session}
  }
}

This will allow our pages client side to access the session which has the user info. For the App page componnet, we'll do some of the same things we did in signin.

./pages/app/[[...id]].tsx
import { getSession, useSession } from 'next-auth/client'

const App = () => {
  // hooks
  const router = useRouter()
  const [session, loading] = useSession()
  // rest of component
}

In the App page jsx, we need to update the condition on the <Dialog />

if (!session && !loading) {
    return (
      <Dialog
        isShown
        title="Session expired"
        confirmLabel="Ok"
        hasCancel={false}
        hasClose={false}
        shouldCloseOnOverlayClick={false}
        shouldCloseOnEscapePress={false}
        onConfirm={() => router.push('/signin')}
      >
        Sign in to continue
      </Dialog>
    )
  }

This will show a modal if a user is not authenticated. We can then pass the session to our <User /> component.

<User user={session.user} />

That's it for protecting our only App page. Next, we're learn how to connect to our DB and use it.