Difficulty Implementing JWT Authentication in Node.js Backend

I’m currently working on a Node.js backend for a web application, and I’m facing challenges while trying to implement JWT (JSON Web Token) authentication. I’ve followed various tutorials and documentation, like this one but I’m still encountering issues with the authentication flow. I’m using Express.js for my API routing and MongoDB for data storage.

Here’s a simplified version of my authentication code:

// auth.js

const jwt = require('jsonwebtoken');
const secretKey = 'mysecretkey';

// ... (other imports and middleware setup)

router.post('/login', async (req, res) => {
  const { email, password } = req.body;

  // Check if email and password are valid
  // If valid, generate a JWT token
  const user = await User.findOne({ email });

  if (!user || user.password !== password) {
    return res.status(401).json({ message: 'Invalid credentials' });
  }

  const token = jwt.sign({ userId: user._id }, secretKey);

  return res.json({ token });
});

// ... (other routes and middleware)

Despite generating the JWT token successfully, when I try to use this token to access protected routes, I’m still getting unauthorized responses. I’ve made sure to include the token in the request header, but something seems to be missing.

Could anyone guide me on what I might be overlooking in this implementation? Is there a common pitfall when setting up JWT authentication in a Node.js backend with Express? Any advice or insights would be greatly appreciated. Thank you in advance!