I'm facing an intriguing challenge with my React project, which involves user authentication and the backend is deployed on render. Specifically, the cookies that should be generated after a successful login are not being created in the deployed environment. The interesting part is that when I run the project locally, everything works smoothly, and the cookies are generated as expected upon successful authentication. However, when I deploy the same project on Render and proceed to log in, although the login process is successful, the anticipated cookies remain absent.
I'm here to share my situation and provide relevant code snippets that might shed light on the issue. If you require additional parts of the code for further diagnosis, please feel free to let me know in the comments section.
Middleware:
const jwt = require("jsonwebtoken");
const User = require("../models/userSchema");
const authenticate = async (req, res, next) => {
try {
const token = req.cookies.amazon;
if (!token) {
return res.status(401).send("Unauthorized: No token provided");
}
const verifyToken = jwt.verify(token, process.env.JWT_SECRET);
const rootUser = await User.findOne({
_id: verifyToken._id,
"tokens.token": token,
});
if (!rootUser) {
throw new Error("User Not Found");
}
req.token = token;
req.rootUser = rootUser;
req.userID = rootUser._id;
next();
} catch (error) {
console.error("Authentication Error:", error);
res.status(401).send("Unauthorized: Invalid token");
}
};
module.exports = authenticate;
controller:
//Login Controller
const loginController = async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: "Please fill in all the details" });
}
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ error: "User not found" });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).json({ error: "Invalid credentials" });
}
const token = await user.generateAuthToken();
res.cookie("amazon", token, {
expires: new Date(Date.now() + 24 * 60 * 60 * 1000),
httpOnly: true,
});
res.status(200).json(user);
} catch (error) {
console.error("Error during login:", error);
res.status(500).json({ error: "An error occurred" });
}
};
UserSchema:
const mongoose = require("mongoose");
const validator = require("validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const userSchema = new mongoose.Schema({
fname: {
type: String,
required: true,
trim: true,
},
email: {
type: String,
required: true,
unique: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error("not valid email address");
}
},
},
mobile: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
minlength: 6,
},
cpassword: {
type: String,
required: true,
minlength: 6,
},
role: {
type: String,
default: "user",
},
tokens: [
{
token: {
type: String,
required: true,
},
},
],
carts: Array,
});
userSchema.pre("save", async function (next) {
if (this.isModified("password")) {
this.password = await bcrypt.hash(this.password, 12);
this.cpassword = await bcrypt.hash(this.cpassword, 12);
}
next();
});
userSchema.methods.generateAuthToken = async function () {
try {
const token = jwt.sign({ _id: this._id }, process.env.JWT_SECRET, {
expiresIn: "1d",
});
this.tokens.push({ token });
await this.save();
return token;
} catch (error) {
console.log(error);
}
};
userSchema.methods.addcartdata = async function (cart) {
try {
this.carts.push(cart);
await this.save();
return this.carts;
} catch (error) {
console.log(error + "Error while adding data to cart");
}
};
const User = mongoose.model("User", userSchema);
module.exports = User;
cors configuration:
app.use(cors({ origin: "http://localhost:3000", credentials: true }));
If anyone has experienced a similar situation where cookies are not being generated after a successful login on a Netlify deployment, your guidance would be greatly appreciated. I wanted to overcome this issue and successfully host my site.
Thank you all in advance for your assistance!