Next.js Discord

Discord Forum

firebase auth with nextjs

Unanswered
Horned Lark posted this in #help-forum
Open in Discord
Horned LarkOP
How can I modify my custom higher-order component (HOC) to handle authentication with Firebase so that when a user logs out and tries to register, they are navigated to the login screen instead of being redirected to the home screen?

3 Replies

Horned LarkOP
import { auth } from "@/firebase/firebaseConfig";
import { useRouter } from "next/router";
import { ComponentType, useEffect } from "react";
import { useAuthState } from "react-firebase-hooks/auth";
export function withPublic<T extends Record<string, unknown>>(
  Component: ComponentType<T>
) {
  return (props: T) => {
    const [user] = useAuthState(auth);
    const router = useRouter();

    useEffect(() => {
      if (user && typeof window !== "undefined") {
        router.replace("/");
      }
    }, [user]);

    if (user) {
      return <h1>Loading...</h1>;
    }

    return <Component {...props} />;
  };
}
import { auth } from "@/firebase/firebaseConfig";
import { useRouter } from "next/router";
import { ComponentType, useEffect } from "react";

import { useAuthState } from "react-firebase-hooks/auth";
export function withProtected<T extends Record<string, unknown>>(
  Component: ComponentType<T>
) {
  return (props: T) => {
    const router = useRouter();
    const [user] = useAuthState(auth);
    useEffect(() => {
      if (!user && typeof window !== "undefined") {
        router.replace("/signup");
      }
    }, [user]);

    if (!user) {
      return <h1>Loading...</h1>;
    }

    return <Component {...props} />;
  };
}
js