I attempted to store a cookie in the client's browser using Nextjs 14 app router within the API folder, but unfortunately, it did not function as expected
Below is the provided code snippet:
app/api/auth/login/route.js
const { NextResponse } = require("next/server");
import connect from "@/app/lib/mongodb";
import MemberModel from "@/app/models/Member.model";
import Notifications from "@/app/models/Notifications";
import { cookies } from "next/headers";
const CryptoJS = require("crypto-js");
export async function POST(req) {
const data = await req.json()
await connect()
let userdata = await MemberModel.find({
email: data.email
})
if (userdata.length === 0) {
return NextResponse.json({ uid: false })
}
if ((userdata[0].email === data.email) && ((CryptoJS.AES.decrypt(userdata[0].password, process.env.CRYPTO_SECRET_KEY).toString(CryptoJS.enc.Utf8)) === data.password)) {
const oneDay = 24 * 60 * 60 * 1000
cookies().set('email', (CryptoJS.AES.decrypt(userdata[0].password, process.env.CRYPTO_SECRET_KEY).toString(CryptoJS.enc.Utf8)), { expires: Date.now() + oneDay })
await Notifications.create({
msg: `User login with email : ${userdata[0].email}`
})
return NextResponse.json({ uid: true })
} else {
return NextResponse.json({ uid: false })
}
}