Checking if a session exists on the frontend
To check if a session exists, you can use the doesSessionExist
method:
// frontend code
import React from "react";
import Session from 'supertokens-auth-react/recipe/session';
// Authenticated only component
class Dashboard extends React.Component {
constructor(props) {
this.state = {
sessionExists: Session.doesSessionExist()
};
}
render() {
if (!this.state.sessionExists) {
// user is not logged in, redirect.
window.location.href = "/";
return null;
}
return (
// Your component for logged in user.
)
}
}
Do not call
doesSessionExist
inside therender
function as it reads from the browser storage.