ARTICLE AD BOX
I'm developing an internal application for my company using Node.js, Express, TypeORM, and a SQL database. I currently have a User entity responsible for authentication.
The login flow is supposed to work like this:
The user accesses www.mysite.com/login
After successful authentication, the backend generates a JWT
The frontend redirects the user to /dashboard
Protected routes should validate the JWT through an authentication middleware
Here is part of my login route and token generation logic:
async function generateToken(user: any) { return jwt.sign( { id: user.id, username: user.username, }, process.env.JWT_SECRET as string, { expiresIn: "1h" }, ); } async function logUser(username: string, password: string) { const userServiceInstance = new userService(); const users = await userServiceInstance.getUsers(); const user = users.find( (u) => u.username === username && u.password === password, ); if (!user) { return null; } else { const token = await generateToken(user); return token; } } router.post("/login", async (req, res) => { const { username, password } = req.body; const token = await logUser(username, password); if (!token) { return res .status(401) .json({ message: "Invalid credentials", token: null }); } return res.json({ message: "Login successful", token }); });The authentication middleware works correctly when tested with Postman.
My problem happens in the browser flow:
after a successful login, the frontend redirects the user to /dashboard, but the middleware returns "Token not provided".
I believe the issue is related to how I should store and send the JWT from the frontend in subsequent requests.
How can I store the JWT on the frontend and send it in the Authorization header for protected routes/pages in my app?
