401 Unauthorized Error When Fetching User Profile in React, Despite Valid Token

I have a React application where I fetch user profiles from my backend API. It was working fine before, but now I keep getting a 401 Unauthorized error when I attempt to fetch the user profile, even though I’m certain that the token is valid.

Here’s my relevant code:

ProfilePage.jsx:

import { useEffect, useRef, useState } from "react";
import { Link, useParams, useNavigate } from "react-router-dom";
import Posts from "../../components/common/Posts";
import ProfileHeaderSkeleton from "../../components/skeletons/ProfileHeaderSkeleton";
import EditProfileModal from "./EditProfileModal";
import { useQuery } from "@tanstack/react-query";
import useFollow from "../../hooks/useFollow";
import useUpdateUserProfile from "../../hooks/useUpdateUserProfile";

const ProfilePage = () => {
    const [feedType, setFeedType] = useState("posts");
    const { username } = useParams();
    const navigate = useNavigate();
    const { follow, isPending } = useFollow();
    const { data: authUser } = useQuery({ queryKey: ["authUser"] });
    const token = localStorage.getItem('token');

    const { data: userProfile, isLoading, refetch, error } = useQuery({
        queryKey: ["userProfile", username],
        queryFn: async () => {
            const res = await fetch(`http://127.0.0.1:8000/profile/${username}/`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json',
                },
            });

            if (!res.ok) {
                const responseText = await res.text();
                console.error("Error response:", responseText);
                throw new Error(responseText || "Something went wrong");
            }
            return await res.json();
        },
    });

    useEffect(() => {
        if (!authUser) {
            navigate('/login');
        } else {
            refetch();
        }
    }, [authUser, navigate, refetch]);

    // ...rest of the component code
};

export default ProfilePage;

Console Log Output:

When I try to fetch the user profile, I see this in the console:

Error response: {"error":"Unauthorized"}

Notes:

  • The token is stored in local storage and is retrieved correctly.
  • The API works when accessed directly via the browser.
  • CORS settings on the backend are correctly configured.

Questions:

  • What could be causing the 401 Unauthorized error despite using a valid token?
  • Are there any specific troubleshooting steps I should follow to resolve this issue?
  • Is there a chance that the token could be expired or invalid without any indication?

Any assistance would be greatly appreciated!