performing server-side authentication with t3-app stack before rendering the index page

My root pages/index.tsx page is functioning as expected: a useSession() call is made to see if there's an active session, and either a splash page or a simple "you're logged in" message is shown depending on whether or not the user is authenticated.
import { useSession } from 'next-auth/react'
import Head from 'next/head'

import Splash from '~/components/Splash'
import LoggedIn from '~/components/LoggedIn'

export const Home = () => {
const { data: session, status } = useSession()
return (
<>
<Head>
<title>App</title>
<meta
name="description"
content="App description."
/>
<link rel="icon" href="/favicon.ico" />
</Head>
{ status === "unauthenticated" ? <Splash/> : <></> }
{ status === "authenticated" ? <LoggedIn session={session}/> : <></> }
</>
)
}

export default Home
import { useSession } from 'next-auth/react'
import Head from 'next/head'

import Splash from '~/components/Splash'
import LoggedIn from '~/components/LoggedIn'

export const Home = () => {
const { data: session, status } = useSession()
return (
<>
<Head>
<title>App</title>
<meta
name="description"
content="App description."
/>
<link rel="icon" href="/favicon.ico" />
</Head>
{ status === "unauthenticated" ? <Splash/> : <></> }
{ status === "authenticated" ? <LoggedIn session={session}/> : <></> }
</>
)
}

export default Home
However, my implementation has a clear flaw: by passing the page first, then performing authentication, my page is briefly displaying as blank before rendering the correct component. For this reason, I'm looking to authenticate on the server first, then return the right component with a server-side-rendered index page. I am guessing that the way to do this is to have the call to the root / be handled by a custom router first, which then passes the session data as a prop to the index page, but I'm not sure how to do so. My understanding is that pages/_app.tsx must render first, without the influence of a router before it, for the application to work. What do you suggest? For added context: I'm using all the tools scaffolded by t3-app related to this, meaning Next, tRPC, and NextAuth are in use.
2 Replies
Neto
Neto2y ago
you can use a middleware to redirect before the page
Neto
Neto2y ago
Want results from more Discord servers?
Add your server