Back

Best Way to Check if Session exists

  • 0
  • Auth
  • Web
  • Cloud
Chris Nowicki
7 May, 2024, 17:55

I am working on an app with a cohort team and we are using createEmailPasswordSession ... all of this is being run in nextJs via a context provider.

TypeScript
useEffect(() => {
    const getSession = async () => {
      try {
        await account.getSession('current');
        console.log('User is signed in');
      } catch (error) {
        console.log(error);
      }
    };
    getSession();
  }, []);

this is great if a session exists. but if it doesn't it returns an error ... is there a better way to check if a session exists.

goal is on page loads to route user to a dashboard or not based on if they are logged in.

TL;DR
To check if a session exists without causing errors, you can use a conditional check like this: ```js useEffect(() => { const getSession = async () => { const userSession = await account.getSession('current').catch(e => null); if(userSession) { console.log('User is signed in'); // Redirect user to dashboard } else { console.log('No user session found'); // Redirect user to login page } }; getSession(); }, []); ```
Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more