Next.js Discord

Discord Forum

Whats the best way to fetch user data?

Unanswered
Pond loach posted this in #help-forum
Open in Discord
Pond loachOP
I am wondering what the best method of fetching user data is for displaying it in a client component. I am using a auth system using JWT tokens. I want to optimize this as its probably not the best way of fetching the data. This is my code:

navbar.tsx:
 const isLoggedIn = useLogStore((state) => state.isLoggedIn);
   const setLoggedIn = useLogStore((state) => state.setLoggedIn);
   const [loading, setLoading] = useState(true);

  const fetchUser = useCallback(async () => {
    try {
      if (isLoggedIn) {
        const userData = await getUser();
        setUser(userData);
      } else {
        setUser(null);
      }
    } catch (error) {
      console.error("Failed to fetch user:", error);
    } finally {
      setLoading(false);
    }
  }, [isLoggedIn]);

  useEffect(() => {
    fetchUser();
  }, [fetchUser]);

  if (loading) {
    return null; 
  }


auth.ts:
export const getUser = async () => {
  try {
    const tokenCookie = cookies().get("token")?.value;
    if (!tokenCookie) return null;

    const decodedToken = jwt.verify(tokenCookie, "SECRET KEY");
    const userId = decodedToken.userId;

    const response = await fetch("http://localhost:4000/api/auth/verify", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ userId }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      return { error: errorText, code: response.status };
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Login failed:", error);
    return { error: "Failed to login", code: 500 };
  }
};


server.js:
app.post("/api/auth/verify", async (req, res) => {
  const { userId } = req.body;

  if (!userId) {
    return res.status(401).send("User ID not provided");
  }

  const user = await User.findOne({ _id: userId });

  if (!user) {
    return res.status(401).send("Invalid user");
  }


  res.json(user);
});

13 Replies

Pond loachOP
bump
are you using nextjs?
In a express, app, I just created a simple GET route for fetching data
@Anay-208 In a express, app, I just created a simple GET route for fetching data
Pond loachOP
Isnt that what I have done?
with a express app, thats only one of the best options
I'm not sure if there is any other option available
Other option is to use ejs and directly pass it to client, not sure if that works with frontend react
Pond loachOP
Bump
Pond loachOP
Bump
Pond loachOP
bump
Since you've already got the most common options available with express, I'm not expecting anyone else to reply with you
Pond loachOP
bump