Authenticated React Routes redirect to / - reactjs

I have a react routing problem I cannot figure out. I have authenticated routes to everything except my login page. The authentication is working correctly and I can navigate around the page when clicking buttons and links but when I type in the route directly to the URL I am redirected to localhost:3000/ . I know why this is happening I just cannot think of a fix for it. Below is all related code. The main problem is the useEffect hook in the login component redirecting to / .
When I type in the url something like localhost:3000/user I am sent to localhost:3000/
What can I do instead?
PrivateRoute.js
const PrivateRoute = ({ component: Component, ...rest }) => {
const authContext = useContext(AuthContext);
const { isAuthenticated } = authContext;
return (
<Route
{...rest}
render={props =>
!isAuthenticated ? <Redirect to='/login' /> : <Component {...props} />
}
/>
);
};
Login.js
const Login = props => {
useEffect(() => {
if (isAuthenticated) {
props.history.push('/');
}
}, [error, onLoad, isAuthenticated, props.history]);
useEffect(() => {
onLoad();
}, [error, onLoad, isAuthenticated, props.history]);
}

Related

How to redirect to another component after google signin in react

I want to redirect to <Chats /> component after the user has signed in through their gmail ID. I also want the uid and userName to be send as props to the component, but I'm not able to redirect to that. I've tried <Navigate /> inside the promise, I've tried window.location.replace('') too. <Navigate /> seems to do nothing and window.location.replace('') redirects but the props are empty, I have no idea what is happening, can anyone help?
Here is the code:
import React, {useState} from 'react'
import { signInWithPopup, signOut } from 'firebase/auth'
import { auth, db, provider } from './firebase-config'
import { set, ref, onValue } from 'firebase/database'
import { BrowserRouter as Router, Routes, Route, Navigate} from 'react-router-dom'
import Chats from './components/Chats'
import Homepage from './components/Homepage'
const App = () => {
const [uid, setUid] = useState('')
const [userName, setUserName ] = useState('')
const [redirect, setRedirect] = useState(false)
const signInWithGoogle = () => {
signInWithPopup(auth, provider)
.then(result => {
setUid(result.user.uid)
setUserName(result.user.displayName)
setRedirect(true)
}).catch(err => console.log(err))
}
const signOutWithGoogle = () => {
signOut(auth, provider)
setUserName('')
setRedirect(false)
}
redirect && (<Navigate to='/chats' />)
return (
<Router>
<Routes>
<Route path="/" element={<Homepage signInWithGoogle={signInWithGoogle} signOutWithGoogle={signOutWithGoogle} />} />
<Route path="/chats" element={<Chats uid={uid} name={userName}/>} />
</Routes>
</Router>
)
}
export default App
you can put both homepage and chats under the same url path and render the page that meets the requirements
<Routes>
<Route path="/" element={uid || userName ? <Chats uid={uid} name={userName}/> :<Homepage signInWithGoogle={signInWithGoogle} signOutWithGoogle={signOutWithGoogle} />} />
</Routes>
or
<Routes>
{uid || userName ?
<Route path="/chats" element={<Chats uid={uid} name={userName}/>} />
:
<Route path="/" element={<Homepage signInWithGoogle={signInWithGoogle} signOutWithGoogle={signOutWithGoogle} />} />
}
</Routes>
Issues
You can't return JSX from a callback and expect it to be rendered into the DOM and do anything.
Don't use the window.location method as this will reload the page, thus remounting your app, so any React state will be lost if it wasn't persisted to localStorage or similar.
Solution 1
Use the useNavigate hook to access the navigate function and issue an imperative redirect with the appropriate data sent along in route state. In order for the App component to use the useNavigate hook though, you will need to lift the Router above it in the ReactTree.
Example:
import { Routes, Route, useNavigate } from 'react-router-dom';
const App = () => {
const navigate = useNavigate();
const signInWithGoogle = () => {
signInWithPopup(auth, provider)
.then(result => {
const { displayName, uid } = result.user.uid;
navigate(
"/chats",
{
replace: true,
state: { uid, userName: displayName },
}
);
})
.catch(err => console.log(err));
};
const signOutWithGoogle = () => {
signOut(auth, provider);
setUserName('');
setRedirect(false);
};
return (
<Routes>
<Route path="/" element={<Homepage signInWithGoogle={signInWithGoogle} signOutWithGoogle={signOutWithGoogle} />} />
<Route path="/chats" element={<Chats />} />
</Routes>
);
};
index.js or wherever App is rendered
import { BrowserRouter as Router } from 'react-router-dom';
...
<Router>
<App />
</Router>
Chat
Use the useLocation hook to access the passed route state values.
const { state } = useLocation();
...
const { uid, userName } = state || {};
Solution 2
If you don't want to send the data in route state you could try using the local uid and userName state and still use the navigate function to imperatively redirect. You'll still need to lift the Router up the ReactTree.
Example:
const App = () => {
const navigate = useNavigate();
const [uid, setUid] = useState('');
const [userName, setUserName ] = useState('');
const signInWithGoogle = () => {
signInWithPopup(auth, provider)
.then(result => {
setUid(result.user.uid);
setUserName(result.user.displayName);
navigate("/chats", { replace: true });
})
.catch(err => console.log(err));
};
const signOutWithGoogle = () => {
signOut(auth, provider);
setUserName('');
setRedirect(false);
};
return (
<Routes>
<Route path="/" element={<Homepage signInWithGoogle={signInWithGoogle} signOutWithGoogle={signOutWithGoogle} />} />
<Route path="/chats" element={<Chats uid={uid} name={userName}/>} />
</Routes>
)
};
In Firebase, there's one function that can help you to implement some code when the authentication change (i.e.: after logging in using an email, after signing up, after logging out, ...), which is:
onAuthStateChanged(auth: Auth, nextOrObserver: NextOrObserver<User>, error?: ErrorFn, completed?: CompleteFn): Unsubscribe;
Where:
auth: The Auth Instance
nextOrObserver: a callback triggered on authentication change
error: a callback triggered on error
completed (optional): a callback triggered when observer is removed
You can read more at: https://firebase.google.com/docs/reference/js/auth.md#onauthstatechanged
Basically, when using this function, you are subscribing to the authentication observer, and this function returns an unsubscribe function. Hence, this is can be perfectly used with useEffect in React. After seeing your problem, you can put these lines into the App component:
useEffect(() => {
const unsubscribe = onAuthStateChanged(user => {
// When no user is logged in and the path is '/chats' => redirect to login page
if(user === null && window.location.href.includes('/chats')) {
if(window.location.href.includes('/chats')) return; // This is important, if this line is not presented, the page will reload infinitely
window.location.href = '/'; // Redirect to '/'
}
// After user is logged in => redirect to '/chats'
if(user !== null && window.location.href.includes('/')) {
if(window.location.href.includes('/')) return;
window.location.href = '/chats'; // Redirect to '/chats'
}
});
return unsubcribe; // This must also included
})
When seeing your code, I see that you put all authentication methods and states in App component. I recommend you to create a React context that contains those lines of code (and also the above code), since they should be global.

React Component not showing updated state changes from custom Hook

I'm trying to get some auth experience and I've got React with React Router, I found a custom auth check for routes that I thought looked good, and tried to implement. Basically it would sign the user in, change the auth value to true and be able to call on that auth value from the hook to check.
Here's my codesandbox, my problem is I have to use AWS Cognito for this project so the sign in call has to be from an async function and not through a promise...
Clicking 'sign in check' calls handleLogin and starts the async function in the useAuthHook with signIn, which sets authed to true via an effect hook. That change is reflected by using the 'auth check' button, but when trying to navigate to a protected route the console logs the default values.
Here's the steps;
...
<Button variant="primary" onClick={handleLogin} type="button">
sign in check
</Button>
...
const handleLogin = () => {
signIn();
};
Now the signIn hook from useAuthHook;
async signIn() {
const user = "totally real"; //AWS await request
testValue = "a diff string";
if (user) {
setUser(user);
console.log(authed, user);
return "/storageSolution";
}
}
the effect hook that updates a ref hook and a useState hook(testing both cases);
React.useEffect(() => {
if (user) {
authed.current = true;
setStateAuth(true);
}
}, [user]);
both stateAuth and the authed ref are returned along with the earlier signIn, and used in RequireAuth before my routes;
export function RequireAuth({ children }) {
const location = useLocation();
const { authed, user, stateAuth } = useAuth();
console.log(authed, user, stateAuth);
return authed === true ? (
children
) : (
<Navigate to="/" replace state={{ path: location.pathname }} />
);
}
but clicking protected route check after signing in shows default values in the console, whereas clicking auth check shows the updates values.
I found https://reactjs.org/docs/hooks-faq.html#why-am-i-seeing-stale-props-or-state-inside-my-function this on stale state, but neither of the reasons it gives seem to be the problem. I've got several different ways of updating and reading that value, but none work. What am I missing?
React hooks don't share state. Move all the state and logic from the useAuth hook into the AuthProvider component. After this is done the useAuth hook simply returns the current authContext value.
Example:
const authContext = React.createContext();
export function useAuth() {
return React.useContext(authContext);
}
export function AuthProvider({ children }) {
const authed = React.useRef(false);
const [user, setUser] = React.useState();
const [stateAuth, setStateAuth] = React.useState(false);
let testValue = "some string";
React.useEffect(() => {
if (user) {
authed.current = true;
setStateAuth(true);
}
}, [user]);
return (
<authContext.Provider
value={{
authed,
user,
testValue,
stateAuth,
async signIn() {
const user = "totally real"; // where the await auth req would be
testValue = "a diff string";
if (user) {
setUser(user);
console.log(authed, user);
return "/storageSolution";
}
}
}}
>
{children}
</authContext.Provider>
);
}
index.js
Import and wrap the app with the AuthProvider component.
...
import { RequireAuth, AuthProvider } from "./useAuthHook";
...
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<AuthProvider>
<BrowserRouter>
<Routes>
<Route path="/" element={<LoginSignup />} />
<Route
path="/storageSolution"
element={
<RequireAuth>
<StorageSolution />
</RequireAuth>
}
/>
<Route path="/secret" element={<SecretRoute />} />
</Routes>
</BrowserRouter>
</AuthProvider>
</React.StrictMode>,
rootElement
);

private routing v6 react

I am trying to implement private routing to my react web application. I have a login, a sign app and a home page, and i want the user to access the homepage only if he is logged in or signed in. I am using Firebase authentication.
I know that my private route component is wrong but because i am new i don't know how to fix it.
I get the error that currentuser is undefined.
Thank you!
PrivateRoute.js
export default function PrivateRoute({ children }) {
const currentUser = useAuth()
console.log(currentUser.email)
return currentUser ?(
<Navigate to="/home" />
) : (
<Navigate to="/signin" />
);
App.js
function App() {
return (
<Routes>
<Route restricted={true} path='/signin' element={<SignInSide/>}/>
<Route
path="/home"
element={
<PrivateRoute>
<Home/>
</PrivateRoute>
}
/>
<Route path='/signup' element={<SignUpside/>}/>
</Routes>
useAuth function in firebase.js
// Initialize Firebase
export const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export function useAuth() {
const [ currentUser, setCurrentUser ] = useState();
useEffect(() => {
const unsub = onAuthStateChanged(auth, user => setCurrentUser(user));
return unsub;
}, [])
return currentUser;
}
Your PrivateRoute component does not make sense, since it is not using the children prop. You should either redirect to the signin page when you don't have a user, or display the children, when you have a user, isn't it ?
It could look like this :
export const PrivateRoute = ({ children }) => {
const currentUser = useAuth()
return currentUser ? children : <Navigate to="/signin" />;
};
However, your error doesn't come from the router, but rather from your useAuth hook it seems. Initially, your user is undefined, so it is normal that you get an error saying this.
If you want to logout the email of the user, try to do the following instead:
if(currentUser)
console.log(currentUser.email)
This way, it will not be undefined.
Furthermore, there is no restricted prop in the Route component of react-router, in the v6.
I hope it solves your issue, otherwise please provide a reproducible example, so it is easier to locate the issue you are facing.
I actually found the problem.
i needed to use context provider and then wrap the app with it
export const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null);
const [pending, setPending] = useState(true);
useEffect(() => {
auth.onAuthStateChanged((user) => {
setCurrentUser(user)
setPending(false)
});
}, []);
if(pending){
return <>Loading...</>
}
return (
<AuthContext.Provider
value={{
currentUser
}}
>
{children}
</AuthContext.Provider>
);
};

How to keep authenticated state on refresh?

I'm using firebase authentication for my app. I used useAuth hook from here. Integrate with react-router guide about redirect (Auth).
SignIn,SignOut function is working as expected. But when I try to refresh the page. It redirects to /login again.
My expected: Redirect to / route when authenticated.
I tried to add this code in PrivateRoute.js
if (auth.loading) {
return <div>authenticating...</div>;
}
So I can refresh the page without redirect to /login but it only show authenticating... when click the log out button.
Here is my code: https://codesandbox.io/s/frosty-jennings-j1m1f?file=/src/PrivateRoute.js
What I missed? Thanks!
Issue
Seems you weren't rendering the "authenticating" loading state quite enough.
I think namely you weren't clearing the loading state correctly in the useEffect in useAuth when the initial auth check was resolving.
Solution
Set loading true whenever initiating an auth check or action, and clear when the check or action completes.
useAuth
function useProvideAuth() {
const [loading, setLoading] = useState(true); // <-- initial true for initial mount render
const [user, setUser] = useState(null);
// Wrap any Firebase methods we want to use making sure ...
// ... to save the user to state.
const signin = (email, password) => {
setLoading(true); // <-- loading true when signing in
return firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then((response) => {
setUser(response.user);
return response.user;
})
.finally(() => setLoading(false)); // <-- clear
};
const signout = () => {
setLoading(true); // <-- loading true when signing out
return firebase
.auth()
.signOut()
.then(() => {
setUser(false);
})
.finally(() => setLoading(false)); // <-- clear
};
// Subscribe to user on mount
// Because this sets state in the callback it will cause any ...
// ... component that utilizes this hook to re-render with the ...
// ... latest auth object.
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
setUser(user);
} else {
setUser(false);
}
setLoading(false); // <-- clear
});
// Cleanup subscription on unmount
return () => unsubscribe();
}, []);
// Return the user object and auth methods
return {
loading,
user,
signin,
signout
};
}
Check the loading state in PrivateRoute as you were
function PrivateRoute({ children, ...rest }) {
const auth = useAuth();
if (auth.loading) return "authenticating";
return (
<Route
{...rest}
render={({ location }) =>
auth.user ? (
children
) : (
<Redirect
to={{
pathname: "/login",
state: { from: location }
}}
/>
)
}
/>
);
}
Demo
Try this approach, it works for me :
const mapStateToProps = state => ({
...state
});
function ConnectedApp() {
const [auth, profile] = useAuth()
const [isLoggedIn, setIsLoggedIn] = useState(false)
useEffect(() => {
if (auth && auth.uid) {
setIsLoggedIn(true)
} else {
setIsLoggedIn(false)
}
}, [auth, profile]);
return (<Router>
<Redirect to="/app/home"/>
<div className="App">
<Switch>
<Route path="/home"><Home/></Route>
<Route path="/login"><Login styles={currentStyles}/></Route>
<Route path="/logout"><Logout styles={currentStyles}/></Route>
<Route path="/signup" render={isLoggedIn
? () => <Redirect to="/app/home"/>
: () => <Signup styles={currentStyles}/>}/>
<Route path="/profile" render={isLoggedIn
? () => <Profile styles={currentStyles}/>
: () => <Redirect to="/login"/>}/>
</Switch>
</div>
</Router>);
}
const App = connect(mapStateToProps)(ConnectedApp)
export default App;

React flashing Private Route when User is not authenticated

I'm using react-router-dom to secure the entire application. All routes are protected under a ProtectedRoute component (see code below), which redirects to an external url, a single-sign-on (SSO) page if the user is not logged in.
Problem:
When the user goes to '/home', they get a brief glimpse (a "flash") of the protected route before getting redirected to 'external-login-page.com/' (the login page). How do I avoid the flashing so that the user only sees the login page?
export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
isAuthenticated,
...rest
}) => {
if (!isAuthenticated) { // redirect if not logged in
return (
<Route
component={() => {
window.location.href = 'http://external-login-page.com/';
return null;
}}
/>
);
} else {
return <Route {...rest} />;
}
};
window.location.href can be called earlier to prevent flashing. Also in your specific case what you probably want is to render nothing at all when the user is not authenticated.
The code may look like this:
export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
isAuthenticated,
...rest
}) => {
if (!isAuthenticated) { // redirect if not logged in
window.location.href = 'http://external-login-page.com/';
return null;
} else {
return <Route {...rest} />;
}
};
You might consider the Redirect component
export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
isAuthenticated,
...rest
}) => {
if (!isAuthenticated) {
return <Redirect to='https://external-login-page.com/' />
} else {
return <Route {...rest} />;
}
};
I would guess that invoking window directly + return null is rendering the React app for a split second before the page reloads.
You can use the Redirect component in a simpler way like this.
export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
isAuthenticated,
children,
...rest
}) => {
return <Route {...rest} render={() => isAuthenticated ? children : <Redirect to='http://external-login-page.com/' />}
}
Posting the solution that eventually worked for me: instead of blocking by Router, block by App.
The key is to split your App into two components, AuthenticatedApp and UnauthenticatedApp. From there, lazy load the correct component depending on the user's level of access. This way, if they're not authorized, their browser won't even load AuthenticatedApp at all.
AuthenticatedApp is a component to your entire app, providers, routers, etc. Whatever you had in App.tsx originally should go here.
UnauthenticatedApp is a component that you want your users to see when they're not allowed to access the application. Something like "Not authorized. Please contact admin for help."
App.tsx
const AuthenticatedApp = React.lazy(() => import('./AuthenticatedApp'));
const UnauthenticatedApp = React.lazy(() => import('./UnauthenticatedApp'));
// Dummy function to check if user is authenticated
const sleep = (time) => new Promise((resolve) => setTimeout(resolve, time));
const getUser = () => sleep(3000).then(() => ({ user: '' }));
const App: React.FC = () => {
// You should probably use a custom `AuthContext` instead of useState,
// but I kept this for simplicity.
const [user, setUser] = React.useState<{ user: string }>({ user: '' });
React.useEffect(() => {
async function checkIfUserIsLoggedInAndHasPermissions() {
let user;
try {
const response = await getUser();
user = response.user;
console.log(user);
setUser({ user });
} catch (e) {
console.log('Error fetching user.');
user = { user: '' };
throw new Error('Error authenticating user.');
}
}
checkIfUserIsLoggedInAndHasPermissions();
}, []);
return (
<React.Suspense fallback={<FullPageSpinner />}>
{user.user !== '' ? <AuthenticatedApp /> : <UnauthenticatedApp />}
</React.Suspense>
);
};
export default App;
Read Kent C Dodd's great post about it here [0]!
EDIT: Found another great example with a similar approach, a bit more complex - [1]
[0] https://kentcdodds.com/blog/authentication-in-react-applications?ck_subscriber_id=962237771
[1] https://github.com/chenkie/orbit/blob/master/orbit-app/src/App.js

Resources