React Router for Unauthenticated User

react router login redirect
react router authentication
react router 403
conditional routing in react
react-router before enter
react-router token authentication
react authentication
react authentication best practices

I am using react router in my project. I am trying to protect authenticated user pages from unauthenticated users.

My code is like below

ReactDOM.render(
    <Router>
        <Switch>
            <Route exact path="/" component={Login} />
            <Route exact path="/register" component={Register} />

            if(Auth.isAuthenticated()) {                
                <Route exact path="/dashboard" component={Dashboard} />
            }
            else {
                <Redirect to="/" />
            }
        </Switch>
    </Router>, 
    document.getElementById('root'));

But this <Redirect to="/" /> is not working.

UPDATE

I made another component like below

Authentication.js

import React, { Component } from 'react';
import Auth from '../services/Auth';
import { Redirect} from "react-router-dom";

const memberAreaHOC = WrappedComponent => {
    class Authentication extends Component {
        render() {
            if ( ! Auth.isAuthenticated()) {
                return <Redirect to="/login" />
            }
            return <WrappedComponent {...this.props}/>;
        }
    }
}

export default memberAreaHOC;

There are several way to do that, but I did recently is creating a wrapper function to extended my protected routes.

ie:

const memberAreaHOC = WrappedComponent => {
  class MA extends Component {
    render() {
      if ( ! Auth.isAuthenticated()) {
        return <Redirect to="/login" />
      }
      return <WrappedComponent {...this.props}/>;
    }
  }
}

and now in your routes definition:

<Router>
    <Switch>
        <Route exact path="/" component={Login} />
        <Route exact path="/register" component={Register} />

        <Route exact path="/dashboard" component={memberAreaHOC(Dashboard)} />

    </Switch>
</Router>

You can see, I wrapped Dashboard with our new memberAreaHOC

memberAreaHOC(Dashboard)

Protected routes and authentication with React Router v4, learn how to create authenticated routes (routes that only certain users can access based on their authentication status) using React Router. See the React Router V4 render documentation. If you did want to create a dedicated component, then it looks like you are on the right track. Since React Router V4 is purely declarative routing (it says so

Could you try this?

<Switch>
    <Route exact path="/" component={Login} />
    <Route exact path="/register" component={Register} />
    {
        !Auth.isAuthenticated() && <Redirect to="/" />
    }
    <Route exact path="/dashboard" component={Dashboard} />
</Switch>

Authentication with Redirect ― Scotch.io, We can use the Redirect component supplied to us by react-router-dom to direct this Posted: Jul 20, 2017 Now what we want to do is when the user authenticates (through the login method), they should be redirected to the home (/) page. There are a few different approaches to redirecting with React Router. You can use the imperative history.push method or you can use the declarative <Redirect /> component. In this case, let’s go with <Redirect />.

Wrap requireAuth to those components which needs permission to access. Routes

<Route path="/admindashboard" component={requireAuth(App)}/>

Create a Higher Order Component to authenticate the user.Generally,HOC is created to reuse the functionality where it takes function as an input and gives output as a function.So,in order to authenticate user for each route and for all his authenticated updation or creation it is needed.As the componentWillMount will check his authentication before rendering the wrapped component where as the componentWillUpdate will check for authetication before updating anything in the authenticated user flow.

import React from 'react';
import { connect } from 'react-redux';
import {withRouter} from 'react-router-dom';
import PropTypes from 'prop-types';

export default function(ComposedComponent) {
  class Authenticate extends React.Component {
    componentWillMount() {
      if (!this.props.isAuthenticated) {
         this.props.history.push('/');
      }
    }

    componentWillUpdate(nextProps) {
      if (!nextProps.isAuthenticated) {
        this.props.history.push('/');
      }
    }

    render() {
      return (
        <ComposedComponent {...this.props} />
      );
    }
  }

  Authenticate.propTypes = {
    isAuthenticated: PropTypes.bool.isRequired
  }

  function mapStateToProps(state) {
    return {
      isAuthenticated: state.auth.isAuthenticated
    };
  }

  return withRouter(connect(mapStateToProps, null)(Authenticate));
}

React tips, React tips — How to protect routes for unauthorized access with React Router v4 many ways to protect routes in React, in a recent post I showed how to use Higher Order <p>Please, you need to be authenticated to to view this content</​p> react-router-protected-route. A Route component that redirects unauthenticated users trying to access an auth-required route. Example. The code below assumes isAccessible is true, and will render the protected route.

Private Route, Public Route, and Restricted Route with React Router, Dashboard: a private route that only authenticated user can access to. Sign-in: a restricted route that unauthenticated user can see. To explain more, we don't want  $ create-react-app react-protected-routes I will create all components on the same file App.js just for simplicity, and the next thing to do is import some components: Install the react-router-dom:

React Router: Authenticated Routes, If not, then the user will be redirected to the Login page. Set up our project. First, let's scaffold a typical React entry point index.js. /* index.js */  React is a JavaScript library for building user interfaces. We can also extend it to build multi-page applications with the help of React Router. This is a third-party library that enables routing in our React apps. In this tutorial, we are going to cover everything you need to know to get started with React Router.

VideoAmp/react-router-protected-route: Route component , react-router-protected-route. Build Status. A Route component that redirects unauthenticated users trying to access an auth-required route. This JavaScript library allows you to turn complex UIs into simple and reusable components that can be composed easily together. This post will show you how to build a React application from scratch, using the Stormpath React SDK to add features that allow people to sign up, login, and even view their own user profile.

Comments
  • What do you mean? Share what you did
  • Share your code on the post and what is your error?
  • OK, ssaw the updated code and its exactly what I posted. But what is the error you are having? and how did you use it in your routes? show all the needed stuff so I could help
  • Well that doesn't help much as I want to know if you have console errors. But in a quick look. The new component we created redirect the user to "/login" path. As I can see in the code you posted you have no "/login" path. The Login component is rendered on "/" so update the "memberAreaHOC" to redirect to that path "/"
  • Share your errors! do console.logs inside the different components so we could see where are things getting or not getting into
  • Thanks @Abinthaha. If I use your solution I can not log in. I am staying at login in page. Thanks.
  • Why should I need HOC ? Your solution looks complex.
  • Generally,HOC is created to reuse the functionality.So,in order to authenticate user for each route and for all his authenticated updation or creation it is needed.As the componentWillMount will check his authentication before rendering the wrapped component where as the componentWillUpdate will check for authetication before updating anything in the authenticated user flow.Its very simple.