Authenticated requests after sign in with React Query and NextAuth

Viewed 2102

I'm having troubled sending an authenticated request to my API immediately after signing in to my Nextjs app using NextAuth. The request that is sent after signing in returns data for and unauthenticated user.

I believe the issue is that React Query is using a previous version of the query function with an undefined jwt (which means its unauthenticated). It makes sense because the query key is not changing so React Query does not think it's a new query, but, I was under the impression that signing in would cause loading to be set to true temporarily then back to false, which would cause React Query to send a fresh request.

I've tried invalidating all the queries in the app using queryClient, but that did not work. I've also used React Query Devtools to invalidate this specific query after signing in but it still returns the unauthenticated request. Only after refreshing the page does it actually send the authenticated request.

// useGetHome.js
const useGetHome = () => {
  const [session, loading] = useSession();
  console.log(`session?.jwt: ${session?.jwt}`);
  return useQuery(
    'home',
    () => fetcher(`/home`, session?.jwt),
    {
      enabled: !loading,
    },
  );
}

// fetcher
const fetcher = (url, token) => {
  console.log(`token: ${token}`);  
  let opts = {};
  if (token) {
    opts = {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    };
  }

  const res = await fetch(`${process.env.NEXT_PUBLIC_BACKEND_URL}${url}`, opts);

  if (!res.ok) {
    const error = await res.json();
    throw new Error(error.message);
  }

  return res.json();
}

// Home.js
const Home = () => {
  const { data: home_data, isLoading, error } = useGetHome();
  ...

  return(
    ...
  )
}

Attached is the console immediately after signing in. You can see the the session object contains the jwt after signing in, but in the fetcher function it is undefined.

console after signing in

Any help here is appreciated. Is there a better way to handle authenticated requests using React Query and NextAuth? Thank you!

1 Answers

I have tried a similar situation here and struggled the same thing but the enabled property worked fine for me and it is good to go right now.

https://github.com/maxtsh/music

Just check my repo to see how it works, that might help.

Related