Trying out a new pattern for errors in data fetching. Next.js is not a fan of throwing errors. Instead it recommends returning different shapes for each state. Ref: https://nextjs.org/docs/app/building-your-application/routing/error-handling#handling-expected-errors-from-server-components It requires some more detailing and a bit more refactoring in non webview part, but it is a start. This webview specific implementation should not break web.
36 lines
942 B
TypeScript
36 lines
942 B
TypeScript
import { headers } from "next/headers"
|
|
import { redirect } from "next/navigation"
|
|
|
|
import { overview } from "@/constants/routes/myPages"
|
|
import { serverClient } from "@/lib/trpc/server"
|
|
|
|
import { auth } from "@/auth"
|
|
|
|
import type { LangParams, LayoutArgs } from "@/types/params"
|
|
|
|
export default async function ProtectedLayout({
|
|
children,
|
|
params,
|
|
}: React.PropsWithChildren<LayoutArgs<LangParams>>) {
|
|
const session = await auth()
|
|
/**
|
|
* Fallback to make sure every route nested in the
|
|
* protected route group is actually protected.
|
|
*/
|
|
const h = headers()
|
|
const redirectTo = encodeURIComponent(
|
|
h.get("x-url") ?? h.get("x-pathname") ?? overview[params.lang]
|
|
)
|
|
|
|
if (!session) {
|
|
redirect(`/${params.lang}/login?redirectTo=${redirectTo}`)
|
|
}
|
|
|
|
const user = await serverClient().user.get()
|
|
if (!user || "error" in user) {
|
|
redirect(`/${params.lang}/login?redirectTo=${redirectTo}`)
|
|
}
|
|
|
|
return children
|
|
}
|