Im building an app and I have protected routes. When a user is signed in, they get sent to the dashboard, if not authed then they are directed to the login page.
so far ive been doing this on every protected route
const supabase = createClient();
const {
data: { user },
error,
} = await supabase.auth.getUser();
if (error || !user) {
redirect('/login');
}
this works but it seems redundant to have to do this on every protected route.
I tried to do something like this on layout.tsx so it would be called on every page route but this threw errors.
I then tried to pass a server component inside layout with children props like this
<html
lang="en"
className={ibm_plex_sans.variable + libre_franklin.variable}
suppressHydrationWarning
>
<body>
<ThemeProvider
enableSystem={false}
attribute="class"
defaultTheme="light"
disableTransitionOnChange
>
<AuthProvider user={user}>
<Header user={user} />
<App user={user}>{children}</App>
</AuthProvider>
</ThemeProvider>
</body>
</html>
and inside App.tsx I tried to call redirect like this
const App = ({ children, user }: AppProps) => {
// const router = useRouter();
useEffect(() => {
if (!user) {
redirect('/login');
}
}, [user]);
return <div>{children}</div>;
};
export default App;
but this is giving me an infinite loop. Even if I make it a server component it still gives me infinite loops.
Is there any better way to do server side private routing in next.js besides doing this
const supabase = createClient();
const {
data: { user },
error,
} = await supabase.auth.getUser();
if (error || !user) {
redirect('/login');
}
on every single page?