auto22
auto22

Reputation: 43

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!

Upvotes: 4

Views: 2183

Answers (1)

Nikolai Lehbrink
Nikolai Lehbrink

Reputation: 334

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

Upvotes: 2

Related Questions