Next.js Discord

Discord Forum

Supabase NextJS 13 Auth - Route Group authentication for layouts

Unanswered
Giant Schnauzer posted this in #help-forum
Open in Discord
Giant SchnauzerOP
Looking for a bit of help with Supabase auth and best practice for nextJS 13.


I'm running a nextjs 13 project inside the app directory. I have a folder with a custom layout app/(dashboard) , where I want everything to require login within this folder. So I've created a custom layout.tsx for this (As per nextJS 13 nested layouts - route groups - https://nextjs.org/docs/app/building-your-application/routing/route-groups). I've then tried to make the layout contents only appear if the user is authenticated, if not redirect to the sign-in page. I'm using the nextjs-subscription-payments template (https://github.com/vercel/nextjs-subscription-payments)

I can't seem to find any clear documentation on this, whether it should be done server or client side, and what the correct procedure is for nextJS 13 redirecting layouts.

Could someone please let me know how I can auth correctly for this?

My layout.tsx is super simple with

export default function DashboardLayout({ children }: PropsWithChildren) {
return (
<SupabaseProvider>
<RequireAuth />
<Sidebar>{children}</Sidebar>
</SupabaseProvider>
);
}

Have tried passing children props to the require auth, not sure which is the best practice.


The 'requireAuth.tsx' is below.
import { getSession, } from '@/app/supabase-server';
import { redirect, usePathname } from 'next/navigation';


export default async function RequireAuth() {
const [session] = await Promise.all([
getSession(),
]);
const user = session?.user;

if (!session) {
return redirect('/signin');
sessionStorage.setItem('destination', usePathname());

console.log('no session')
}

else
// console.log('session', session);
if (user?.user_metadata.full_name) {
console.log('logged in as', user?.user_metadata.full_name);
}
else { console.log('logged in as Unknown'); }
return #Unknown Channel</>;

};


Thanks

0 Replies