When a user successfully logs in, their information is stored in a cookie using the "Set-Cookie" response header. However, I am facing an issue where the cookie seems to get lost when making subsequent requests from the client. As a result, the server treats these new requests as unauthorized.
After logging in, the response header looks like this: https://i.sstatic.net/X9wdc.png
But after sending a request following the login, the request header changes: https://i.sstatic.net/fAzY7.png
The codes for the login process and authentication middleware are provided below:
public logIn = async (req: Request, res: Response, next: NextFunction) => {
const logInData: LogInDto = req.body;
const user: UserInterface = await this.User.findOne({ email: logInData.email });
if (user) {
console.log(user);
const passwordMatch: boolean = await this.authService.matchPassword(logInData, user);
console.log(passwordMatch);
if (passwordMatch) {
const token: Token = this.authService.createToken(user);
const cookie: any = this.authService.createCookie(token);
res.setHeader("Set-Cookie", [cookie]);
res.status(200).json(
{
message: "Login success",
user: user
}
);
} else {
next(new CredentialsException());
}
} else {
next(new CredentialsException());
}
}
It appears that there may be some headers missing during the new request made by the client. Below is an example of a client-side request:
const Dashboard: React.FC = () => {
const handleClick = async () => {
const res: any = await axios.get<any>(
"http://localhost:4000/getusers",
{
withCredentials: true
}
);
console.log(res);
}
For further insights, here's the authentication middleware used on the server side:
export async function authMiddleware(req: Request, res: Response, next: NextFunction) {
// Middleware logic here
}
If you encounter issues with losing cookies or unauthorized requests, make sure to check the headers being set during each request.