How to Detect User is Register or Not while Watching Product Details? Using MERN Stack

How to Detect User is Register or Not while Watching Product Details? Using MERN Stack

To check if a user is logged in when looking at product details, use the authentication token from when they signed in. If they're logged in, the token will be in the client (usually in local storage or a cookie). Then, send this token to the server with requests for protected routes or user info.

Here's how you can modify the ProductDetails.js component to check if the user is registered:

import React, { useEffect, useState } from 'react';
import axios from 'axios';

const ProductDetails = ({ match }) => {
  const [product, setProduct] = useState({});
  const [user, setUser] = useState(null);

  useEffect(() => {
    const fetchProduct = async () => {
      try {
        const response = await axios.get(`/api/products/${match.params.id}`);
        setProduct(response.data);
      } catch (error) {
        console.error('Error fetching product details:', error);
      }
    };

    // Fetch product details
    fetchProduct();

    // Check if the user is signed in
    const token = localStorage.getItem('authToken'); // Assuming the token is stored in local storage
    if (token) {
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
      // Make a request to a protected endpoint to get user information
      axios.get('/api/user')
        .then(response => {
          setUser(response.data);
        })
        .catch(error => {
          console.error('Error fetching user details:', error);
        });
    }
  }, [match.params.id]);

  return (
    <div>
      <h2>{product.name}</h2>
      <p>{product.description}</p>
      <p>${product.price}</p>

      {user ? (
        <p>Welcome, {user.username}!</p>
      ) : (
        <p>Please sign in to see more details.</p>
      )}
    </div>
  );
};

export default ProductDetails;

In this example, the code looks for a saved authentication token (localStorage.getItem('authToken')) and includes it in the headers when requesting a protected endpoint (/api/user). If the user is authenticated, the server sends back user details, and the component updates the user state based on that.

Keep in mind that the server-side code for /api/user needs to check the token's validity and give back user details if the token is good. The server-side code might look like:

// Example server-side code for /api/user endpoint verification
app.get('/api/user', authenticateToken, (req, res) => {
  // If the token is valid, req.user contains the user information
  res.json(req.user);
});

function authenticateToken(req, res, next) {
  const token = req.headers.authorization && req.headers.authorization.split(' ')[1];
  if (!token) return res.sendStatus(401);

  jwt.verify(token, 'your-secret-key', (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
}

This is a simple version, and you might want to improve it depending on your needs and safety concerns.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!