I’m in a course trying to finish a full-stack project, and I’m having trouble with two areas when trying to create login functionality: getting my Authorization request header to the backend with a JWT token, and actually attaching the token to the header. Whenever I send the POST request, the token is generated properly, and the Authorization request is created as well (I can see it in the network tab when I inspect), yet when I try to decode the token in my auth middleware by reading the token via the header, it says that the header is undefined.
This is my code for the POST request:
fetch('http://localhost:4000/api/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': "Bearer ${token}",
},
body: JSON.stringify({
email: email,
password: password
}),
}).then( async (res) => {
// other code here
})
And this at the end of my login function that sets the token:
const token = jwt.sign(
{ user_id: user.user_id },
'RANDOM_TOKEN_SECRET',
{ expiresIn: '24h'}
);
console.log(req.headers);
res.status(200).json({
user_id: user.user_id,
token: token
});
I use the console.log(req.headers); to see what request headers display, and Authorization is included. This is what the log returns:
{
host: 'localhost:4000',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101
Firefox/132.0',
accept: '*/*',
'accept-language': 'en-US,en;q=0.5',
'accept-encoding': 'gzip, deflate, br, zstd',
referer: 'http://localhost:3000/',
'content-type': 'application/json',
authorization: 'Bearer token',
'content-length': '43',
origin: 'http://localhost:3000',
connection: 'keep-alive',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-site',
priority: 'u=0'
}
This is my auth middleware:
module.exports = (req, res, next) => {
try {
console.log(req.headers);
const token = req.headers.authorization;
const decodedToken = jwt.verify(token, 'RANDOM_TOKEN_SECRET');
const user_id = decodedToken.user_id;
req.auth = { user_id };
if (req.body.user_id && req.body.user_id !== user_id) {
throw 'Invalid user ID';
}
else {
next();
}
}
catch {
res.status(401).json({
error: new Error('Invalid request')
});
}
};
Here’s where I’m getting my issue: the authorization header disappeared. the console log in my middleware doesn’t have the authorization header in it anymore and I’m not sure why, and I’m not sure of any other way to pass the token to the middleware.
2
Answers
use template literal
Instead of using "Bearer ${token}", use ` (backtick) symbol
Double-check the string interpolation for the Authorization header in the fetch request.
Ensure that your middleware for parsing request bodies is set up correctly.
Verify that the token is correctly generated and sent back in the response.
Correctly extract and verify the token in your auth middleware.
Ensure CORS is properly configured if needed.