How do I refactor this into withAuth
using HOC? Or is it possible to use hooks here?
#3187
-
import { useSession } from 'next-auth/react'
import { LoginPage } from '@/client/components/index'
const Homepage = () => {
const session = useSession()
if (session && session.data) {
return (
<>
<div>Homepage</div>
</>
)
}
return <LoginPage />
}
export default Homepage Basically, I don't want to write the same boilerplate of I want something like: import { withAuth } from '@/client/components/index'
const Homepage = () => {
return (
<>
<div>Homepage</div>
</>
)
}
export default withAuth(Homepage) Or if possible How does everyone does this? This seems to be lot of redundant code. Maybe a new API can be added to I did try doing: import React from 'react'
import { useSession } from 'next-auth/react'
import { LandingPage } from '@/client/components/index'
export const withAuth = (Component: React.ComponentType) => {
const AuthenticatedComponent = (props: JSX.IntrinsicAttributes) => {
const session = useSession()
if (session && session.data) {
return <Component {...props} />
}
return <LandingPage />
}
return AuthenticatedComponent
} But I get an error:
on the line: export default withAuth(Homepage) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
We might move this into a different section in the future (I think the name is misleading/wrong), but check this out: https://next-auth.js.org/getting-started/client#custom-client-session-handling You can also use the |
Beta Was this translation helpful? Give feedback.
-
This article was very helpful for me: https://mahieyin-rahmun.medium.com/part-2-how-to-configure-social-authentication-in-a-next-js-183984761e97 |
Beta Was this translation helpful? Give feedback.
We might move this into a different section in the future (I think the name is misleading/wrong), but check this out:
https://next-auth.js.org/getting-started/client#custom-client-session-handling
You can also use the
useSession
hook with therequired
parameter: https://next-auth.js.org/getting-started/client#require-session