I would like to show Login/register link if user is not authenticated, and Logout link if they are....
r
I would like to show Login/register link if user is not authenticated, and Logout link if they are. Trying to do this with demo application for react
Copy code
npx create-supertokens-app@latest --recipe=emailpassword
. How do I do this pls?
r
Hey @reevolver
r
Hiya
Click on the supertokens-auth-react button on the toggle on the right / top depending on which device you are opening the link on
See the optional session part
r
I was trying to use that. Its for a sidebar menu on all pages, so I dont want it to redirect if they are not logged in, just show a login link/button. The example is for 'If they are not logged in, the user will be redirected to the login page.'
r
See the optional session part
“Optional session on a route”
r
I've adapted the Optional session example thus:
Copy code
function MyDashboardComponent(props: any) {
  let sessionContext = Session.useSessionContext();
  
  if (sessionContext.loading) {
    return <span>Loading...</span>;
  }
  if (sessionContext.doesSessionExist) {
    return <button>Logout</button>;
  } else {
    return <button>Login</button>;
  }
}
This is the at the top level of my react app. So I need to call SuperTokens.init(config) before right for it to know whether loggedin/not/valid session? But the calling init with emailpassword recipie redirects immediatly to show login dialog.
r
You need to call the init function yea
Remove all uses of the SessionAuth wrapper in the app
In our demo app, the home route is protected with SessionAuth which redirects to login screen if not logged in
r
Thx. Im still struggling with this. I have the feeling it should be easier to achieve this. Its a very common use case right?
r
It is fairly easy indeed. Just have to read from the session context provided by the supertokensWrapper
Did you remove the SessionAuth component that’s being used in the demo app?
r
Yes, so then I can detect not logged in, and show login button. But then that button needs to allow the user to login, and protect certain routes for logged in state only?
r
Yea. So when the button is clicked, you redirect to the auth screen
And whichever routes you want to be protected, wrap them with SessionAuth component
r
Thx, sorted now
r
nice!
6 Views