Next.js Discord

Discord Forum

How do I authenticate at the root with two root layouts?

Unanswered
Glen of Imaal Terrier posted this in #help-forum
Open in Discord
Avatar
Glen of Imaal TerrierOP
When users arrive at my app's / root route, I want to authenticate them and then decide whether they see a landing-page-esque UI or whether they see the logged in UI. I don't want to have to have a separate route (/home, /dashboard, etc.) for my logged in view, but I'm not sure if this is something that Next.js supports? I tried using Route Groups + two Root Layouts, but navigating to / lands at one of the two root layouts randomly.

Ideally, my app directory would look something like:
/app
  /(protected)
    /(dashboard)
      ...
    /settings
      ...
    /users
      ...
    layout.tsx
    page.tsx
  /(public)
    /log-in
      ...
    /sign-up
      ..
    layout.tsx
    page.tsx

8 Replies

Avatar
ncls.
Are you using your own code for authentication or any frameworks like NextAuth?
Avatar
European sprat
Maybe there's something with Intercepting Routes you can do?

https://nextjs.org/docs/app/building-your-application/routing/intercepting-routes
Avatar
Glen of Imaal TerrierOP
Supabase Auth!
Avatar
Glen of Imaal TerrierOP
Actually, I think I can achieve this with parallel routes.
My single root layout would have to look like the example in the top left
Image
Avatar
European sprat
ahh yeah i was just reading that page and got to that part too. sounds like what you're looking for
Avatar
Glen of Imaal TerrierOP
I wandered over that to that page from intercepting routes, so thank you 🙏
Avatar
ncls.
I have never worked with that. Basically you have two ways (if we ignore intercepting routes because that's not the use case of it) of accomplishing it: You either to a conditional render (probably partly invalid code because I never worked with Supabase Auth):
import { createClientComponentClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';
// Importing your components, in my case called "LoggedInView" and "LoggedOutView"

export default function Home() {
  const supabase = createServerComponentClient({ cookies });
  const {
    data: { session }
  } = await supabase.auth.getSession();

  return session ? <LoggedInView /> : <LoggedOutView />;
}

or you use middleware rewrite:
import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs';
import { NextResponse } from 'next/server';

export async function middleware(req) {
  const supabase = createMiddlewareClient({ req, res });

  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (user) return NextResponse.rewrite(new URL('/logged-in', req.url));
  return NextResponse.rewrite(new URL('/logged-out', req.url));
}

export const config = {
  matcher: ['/'],
}