0

I'm developing a React application with Next.js and using Supabase for authentication. I have a custom hook called useAuthentication that checks if the user is logged in and redirects them to the login page if not. However, I'm encountering a runtime error stating "TypeError: Cannot read properties of undefined (reading 'user')" in the useAuthentication.js file.

Here is the relevant code:

import { useEffect } from 'react';
import { useRouter } from 'next/router';
import { auth } from '@supabase/supabase-js';
import { supabase } from '../supabase/supabaseConfig';

const useAuthentication = () => {
  const router = useRouter();

  useEffect(() => {
    const checkIfUserIsLoggedIn = async () => {
      const user = await auth.user();
      if (!user) {
        router.push('/login');
      }
    };

    checkIfUserIsLoggedIn();
  }, [router]);

  return null;
};

export default useAuthentication;

I have ensured that I properly initialized the supabase client in my supabaseConfig.js file and that the @supabase/supabase-js package is installed as a dependency. this is my supabaseconfig file:

import { createClient } from "@supabase/supabase-js";


const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASEURL
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASEKEY
export const supabase = createClient(supabaseUrl, supabaseKey);

Could someone please help me understand why I'm getting this error and how to fix it? Thank you!

2
  • auth is undefined. Are you importing the file correctly? Commented Jun 26, 2023 at 10:03
  • yes these are my codes Commented Jun 26, 2023 at 10:06

1 Answer 1

0

The import of auth is incorrect and there is no user method anymore as that was v1 of the supabase-js library, in v2 the method is getUser. You should be using the supabase you import in this file so it should be:

import { useEffect } from 'react';
import { useRouter } from 'next/router';
import { supabase } from '../supabase/supabaseConfig';

const useAuthentication = () => {
  const router = useRouter();

  useEffect(() => {
    const checkIfUserIsLoggedIn = async () => {
    const user = await supabase.auth.getUser();
      if (!user) {
        router.push('/login');
      }
    };

    checkIfUserIsLoggedIn();
  }, [router]);

  return null;
};

export default useAuthentication;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.