#Best practices for authentication checking

9 messages · Page 1 of 1 (latest)

dry snow
#

I am using firebase and using firebase admin api to check for authentication status via cookies.

I am doing this call at the layout.tsx level

import { redirect } from 'next/navigation';

import LoggedIn from '@/components/layouts/logged-in';
import { getCurrentUser } from '@/lib/firebase/firebase-admin';
import InvoicesNav from './invoices-nav';

export const metadata = {
  title: 'Invoices | Acctual',
};

export default async function InvoiceLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const currentUser = await getCurrentUser();

  if (!currentUser) {
    redirect('/login');
  }
  const createInvoiceAction = {
    label: 'Create invoice',
    href: '/invoices/new',
  };

  return (
    <LoggedIn title="Invoices" action={createInvoiceAction}>
      <div className="w-full">
        <InvoicesNav />
        <div className="pt-8 pb-6">{children}</div>
      </div>
    </LoggedIn>
  );
}
export async function getCurrentUser() {
  const session = await getSession();
  if (!(await isUserAuthenticated(session))) {
    return null;
  }

  const decodedIdToken = await auth.verifySessionCookie(session!);
  const currentUser = await auth.getUser(decodedIdToken.uid);
  return currentUser;
}

Is there a more performant way to do this? I have layouts for separate parts of the app that need to be authenticated, but wondering if there's a better way to do this so that it doesn't take long between navigation switches

pastel flintBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

eager turret
dry snow
#

is there an example of this pattern for firebase anywhere? i feel like middleware is the right approach here, page auth makes sense, at data fetching might make sense too cause im using tanstack query with api routes so each data fetch route may be able to do the check and if it returns 401, the frontend redirects to login, interesting

eager turret
eager turret
#

@dry snow do you need anything else?

eager turret
#

@dry snow ?

dry snow
#

All good here, thanks!

pastel flintBOT
#
✅ Success!

This question has been marked as answered! If you have any other questions, feel free to create another post

Jump to answer

[Click here](#1254903330321469561 message)