Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.JS App Router, protected routes, and hiding a layout flicker

I'm using Next.js 13.4.12 and Firebase auth in my application and I want to protect all routes behind /dashboard. I am using the App Router (not the old Pages Router).

My questions:

  1. How can we protect routes with server side logic/middleware (see Edge runtime issue details below)?
  2. How can we protect client components/pages without a "layout" flicker if we are using React context to determine user authentication status?

I'd like to use middleware to protect the routes, but it would require using the firebase-admin sdk. Next.JS middleware uses the Edge runtime though and it does not support Node.JS APIs so the firebase-admin sdk does not work. You get this error: Error: The edge runtime does not support Node.js 'os' module

Ideally, it would function similar to the way next-auth handles it, except we would use the firebase-admin sdk to validate the user's token:

// middleware.ts

export { default } from "next-auth/middleware"

export const config = { matcher: ["/dashboard/:path*"] }

The other alternative is to protect routes on the client side using something like this:

// /src/app/dashboard/page.tsx

'use client';
...

const Dashboard = () =\> {
const { user } = useAuthContext()
const router = useRouter()

    useEffect(() => {
      if (user == null) router.push("/auth/login");
    }, [user]);

return (
\<div\>My Protected Page\</div\>
);
};

export default Dashboard;

With the app router, because I have a layout defined in my layout.tsx file, the dashboard layout flickers before the router pushes the user to the login page.

Thanks!

like image 961
auto22 Avatar asked Oct 17 '25 07:10

auto22


1 Answers

just wanted to mention that there is a library out there, that aims at what I believe, this exact use case. https://github.com/awinogrodzki/next-firebase-auth-edge

like image 100
Nikolai Lehbrink Avatar answered Oct 18 '25 23:10

Nikolai Lehbrink



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!