I used mongo db for login and jwt token in authorization.
The Login response:
{_id: '666d30899f2bb9bfc3d5978d', name: 'demo', email: '[email protected]', token: adfasdfsdfasf}
I can log in with email and password by Login.jsx page
import axios from "axios";
import React, { useState } from "react";
import { useCookies } from "react-cookie";
import { useNavigate } from "react-router-dom";
const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const navigate = useNavigate();
const [, setCookie] = useCookies(["user"]);
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post(
"http://localhost:3000/api/v1/auth/login",
{
email,
password,
}
);
console.log("Login response:", response.data);
// Set user info in a cookie as a JSON string
setCookie("user", JSON.stringify(response.data), { path: "/" });
// Navigate to the department list
navigate("/departments");
} catch (err) {
console.error("Login error:", err);
setError("Invalid email or password");
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<div className="max-w-md w-full space-y-8">
<div>
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
Sign in to your account
</h2>
</div>
<form className="mt-8 space-y-6" onSubmit={handleSubmit}>
{error && (
<div className="rounded-md bg-red-50 p-4">
<div className="flex">
<div className="flex-shrink-0">
<svg
className="h-5 w-5 text-red-400"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fillRule="evenodd"
d="M10 3a1 1 0 00-.707.293l-7 7a1 1 0 000 1.414l7 7a1 1 0 001.414-1.414L4.414 11H17a1 1 0 100-2H4.414l4.293-4.293A1 1 0 0010 3z"
clipRule="evenodd"
/>
</svg>
</div>
<div className="ml-3">
<h3 className="text-sm font-medium text-red-800">{error}</h3>
</div>
</div>
</div>
)}
<div className="rounded-md shadow-sm -space-y-px">
<div>
<label htmlFor="email-address" className="sr-only">
Email address
</label>
<input
id="email-address"
name="email"
type="email"
autoComplete="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
placeholder="Email address"
/>
</div>
<div>
<label htmlFor="password" className="sr-only">
Password
</label>
<input
id="password"
name="password"
type="password"
autoComplete="current-password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
placeholder="Password"
/>
</div>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center">
<input
id="remember-me"
name="remember-me"
type="checkbox"
className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
/>
<label
htmlFor="remember-me"
className="ml-2 block text-sm text-gray-900"
>
Remember me
</label>
</div>
<div className="text-sm">
<a
href="#"
className="font-medium text-indigo-600 hover:text-indigo-500"
>
Forgot your password?
</a>
</div>
</div>
<div>
<button
type="submit"
className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
>
Sign in
</button>
</div>
</form>
</div>
</div>
);
};
export default Login;
But in the Navbar the user information does not show. In the console it shows “Failed to parse user from cookies”
Here is the Navbar.jsx :
import React from "react";
import { useCookies } from "react-cookie";
import { Link, useNavigate } from "react-router-dom";
const Navbar = () => {
const navigate = useNavigate();
const [cookies, , removeCookie] = useCookies(["user"]);
const handleLogout = () => {
// Clear user info from cookies
removeCookie("user", { path: "/" });
// Redirect to login page
navigate("/login");
};
// Retrieve user info from cookies
let user = null;
try {
if (cookies.user) {
user = JSON.parse(cookies.user);
}
} catch (error) {
console.error("Failed to parse user from cookies:", error);
}
console.log("User from cookies:", user);
return (
<div className="max-w-screen-2xl container mx-auto">
<div className="navbar bg-base-100 shadow-md">
<div className="navbar-start">
{/* Dropdown and logo */}
<a className="btn btn-ghost text-xl">BMS</a>
</div>
<div className="navbar-center hidden lg:flex">
{/* Main menu */}
<ul className="menu menu-horizontal px-1">
<li>
<Link to="/">Home</Link>
</li>
<li tabIndex={0}>
<details>
<summary>HR & Payroll</summary>
<ul className="p-2 bg-base-100 shadow-md">
<li>
<Link to="/settings">Settings</Link>
</li>
<li>
<Link to="/employee">Employee Information</Link>
</li>
</ul>
</details>
</li>
</ul>
</div>
<div className="hidden md:block">
{/* Search bar */}
<label className="input input-bordered flex items-center gap-2">
<input type="text" className="grow" placeholder="Search" />
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 16 16"
fill="currentColor"
className="w-4 h-4 opacity-70"
>
<path
fillRule="evenodd"
d="M9.965 11.026a5 5 0 1 1 1.06-1.06l2.755 2.754a.75.75 0 1 1-1.06 1.06l-2.755-2.754ZM10.5 7a3.5 3.5 0 1 1-7 0 3.5 3.5 0 0 1 7 0Z"
clipRule="evenodd"
/>
</svg>
</label>
</div>
<div className="navbar-end flex items-center gap-4">
{user ? (
<div className="flex flex-col items-end">
<span className="text-sm text-gray-700">{user.email}</span>
</div>
) : (
<div className="flex flex-col items-end">
<span className="text-sm text-gray-700">
User information not available
</span>
</div>
)}
{/* Logout button */}
<button className="btn" onClick={handleLogout}>
Logout
</button>
</div>
</div>
</div>
);
};
export default Navbar;
What is the reason and what is the best standard of Login.