Skip to content

Instantly share code, notes, and snippets.

@rohailtaha
Last active June 28, 2024 11:30
Show Gist options
  • Save rohailtaha/140ba93b25e2a01f583374ccd9f11ed3 to your computer and use it in GitHub Desktop.
Save rohailtaha/140ba93b25e2a01f583374ccd9f11ed3 to your computer and use it in GitHub Desktop.
Nextjs Reusables
import { useSession } from "next-auth/react"
import { useRouter } from "next/router"
// It only renders the children if user is authenticated, otherwise it will redirect to
// redirect Url.
function Auth({ children, waitContent = null, redirectUrl }) {
const { data: session, status } = useSession()
const loading = status === "loading"
const router = useRouter()
if (!loading && !session) router.push(redirectUrl)
if (!loading && session) return children
return waitContent
}
export default Auth
import { useSession } from "next-auth/react"
import { useRouter } from "next/router"
// It only renders the children if user is a guest(unauthenticated), otherwise it will redirect to redirect url.
function Guest({ children, waitContent = null, redirectUrl }) {
const { data: session, status } = useSession()
const loading = status === "loading"
const router = useRouter()
if (!loading && session) router.push(redirectUrl)
if (!loading && !session) return children
return waitContent
}
export default Guest
export function serverErrorResponse(message: string): Response {
return Response.json(
{
error: {
type: ERROR_TYPE.ServerError,
message,
},
},
{
status: 500,
}
);
}
export function jsonErrorResponse(
errorType: ERROR_TYPE | string,
message: string,
status: number
): Response {
return Response.json(
{
error: {
type: errorType,
message,
},
},
{
status,
}
);
}
export async function getToken(request: Request): Promise<JWT | null> {
return (await getToken__NextAuth({
req: request as NextRequest,
})) as JWT | null;
}
// We get session using the 'useSession' hook in 'next-auth/react':-
const { data: session, status } = useSession();
// Logging this:-
console.log(session, status);}
// We get:-
1) For Authenticated user:
undefined loading
user loading
user authenticated
2) For Unauthenticated user:
undefined loading
null loading
null unauthenticated
// A component that shows "wait content" until session information is fetched (loading is finished)
// Renders children after fetching session info
// Note: User may or may not have session, this component only waits while session info is being fetched.
import { useSession } from "next-auth/react"
function SessionInfoWaiter({ waitContent = null, children }) {
const { status } = useSession()
if (status === "loading") return waitContent
return children
}
export default SessionInfoWaiter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment