Reactjs Private Routes and React Router

Asked

Viewed 1,118 times

0

You can implement private routes by receiving a JWT token in the header and body information in Reactjs with React Router?

  • Yes it is possible.

  • know some link with tutorial or sample code?

  • 1

    So unfortunately I have no public project with this content, but if I’m not mistaken in the channel of Rocketseat will have some content next to that.

1 answer

1

I use it this way in my applications

const PrivateRoute = ({component: Component, ...rest}) => {
return (

    <Route {...rest} render={props => (
        isAuth() ?
            <Component {...props} />
        : <Redirect to="/signIn" />
    )} />
);
};

This isAuth() is a method that comes from a file I use to see if it is in localstorage

module.exports = {
isAuth(){
    var user = localStorage.getItem('current_user')
    if(!user)
        return false

    return true
}
}

And in your route file only you use Private route when you want to have an authenticated route

<PrivateRoute path="/suaRota" component={ SeuComponent } />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.