Skip to content

Instantly share code, notes, and snippets.

@jmg
Created August 13, 2022 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmg/df09787d8633999bf0868c9cbaba4bca to your computer and use it in GitHub Desktop.
Save jmg/df09787d8633999bf0868c9cbaba4bca to your computer and use it in GitHub Desktop.
import { useEffect, useState } from "react";
import { getAuth } from "@firebase/auth";
import Router from "next/router";
const auth = getAuth()
export const AuthGuard = ({ children, redirectUrl }: any) => {
const [isLoading, setIsLoading] = useState(true);
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(user => {
setIsLoading(false);
setIsAuthenticated(!!user);
});
return () => {
unsubscribe();
}
} , []);
if (isLoading) {
return null;
}
if (!isAuthenticated) {
Router.push(redirectUrl);
}
return children;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment