Guide on setting a client-side cookie in NextJS 14

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 })
    }
}

Answer №1

The Desired Result :

Setting a cookie on the client side

Cause of Issue :

Your response does not include a Set-Cookie header

Solution:

Modify your code from :

return NextResponse.json({ uid: true })

to

return NextResponse.json(
    { uid: true },
    { headers: { 'Set-Cookie': `COOKIE_VALUE` } },
);

Please, Refer to :

Consult the following links for syntax, optional parameters, etc. :

If you still have any questions, feel free to leave a comment.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PHP/AJAX user action history manager

Is there a library available that offers undo/redo functionality with a complete history for a web application? One possible solution could be a system using php/javascript/ajax where you can record the opposite action and variable state for each user acti ...

What is the best way to create a screen capture of a webpage using a URL?

Currently working on a Spring MVC website project, I have implemented a form requesting the user's website URL. Once entered, I aim to display a screenshot of the specified website for the user to view. Contemplating whether to generate the image on ...

Is it possible for javascript to show the user's current location on a google map without using a KML layer?

I need help with loading a KML file using JavaScript and adding a marker to the map at the user's current location. The code I have been working on works fine, but it seems to be missing the geolocation check for the current position. How can I proper ...

Tips for managing CSS/style conflicts in JavaScript/AngularJS applications

I am new to AngularJS and I have a requirement to assign CSS properties to a component at the JavaScript file level. When I debug my code after applying the CSS styles to the component, I can see that all the applied CSS properties are behaving as expected ...

Encountering NodeJs Error 401(Unauthorized) while implementing passport-jwt in my project

I am currently developing an authentication application using Node.js, MongoDB, and the Passport-JWT middleware. I have successfully implemented the login functionality and I am able to obtain a token. However, when trying to access the user profile after ...

Easy-to-use blog featuring Next.js 13 and app router - MDX or other options available

Currently in the process of transitioning a Gatsby website to Next.js (v13.4) and utilizing the new App Router. However, I'm facing some challenges when it comes to migrating the blog section over because there isn't much accurate guidance availa ...

Condense third-party JavaScript libraries

Currently, I am in the process of consolidating a single vendor.min.js file in order to minimize the number of external files being loaded. To accomplish this, I have created the following gulp task: gulp.task('vendor-bundle', function() { gulp ...

Guide to saving HTML form data into localstorage as a JSON string through JavaScript

What's the best way to retrieve form values for localStorage as a JSON string without using JQuery? I tried using a for loop but I'm having trouble.. any hints would be greatly appreciated (I'm still new at this). Thank you! <input type ...

Add the attribute's value to an array

$(document).ready(function() { function randomColor() { return 'rgb(' + Math.round(Math.random() * 255) + ', ' + Math.round(Math.random() * 255) + ', ' + Math.round(Math.random() * 255) + ')' ...

NextJS - Fullcalendar is experiencing issues with loading its style completely

I'm currently working on integrating FullCalendar into a Next.js 13 project (T3 Stack) and facing an issue where the style fails to load properly upon navigating back to the page containing my FullCalendar component for the second time. What I'v ...

Issues with JQuery .attr method not functioning as expected

I'm having trouble with the .attr() function in jQuery. It doesn't seem to be changing the background-color of the div with the id "outline" like I expected. Here's an example of my code: <div id="outline"></div> And here is t ...

Retrieving values from all fields in a dynamic form using VuejsLet's say

In the process of developing an admin panel using Vuejs and tailwind CSS for managing exercises on a page, I have encountered some challenges. My current objective is to insert the dynamic form values into a Firebase real-time database. However, I am stru ...

Display text when hovered over or clicked to insert into an HTML table

I have an HTML table connected with a component field gameArray and I need it to: Show 'H' when the user's cursor hovers over TD (:hover) and the corresponding field in gameArray is an empty string, Fill the gameArray field after a click. ...

Prevent the use of exponential notation with double numbers in GWT

Is there a way to remove the exponent from a double on the client side in GWT? public double evaluate(final double leftOperand, final double rightOperand) { Double rtnValue = new Double(leftOperand * rightOperand); //Need code to remove expone ...

At runtime, the array inexplicably becomes null

Having recently ventured into the world of Ionic framework development, I have encountered a puzzling issue. At runtime, an array inexplicably gets nulled and I am struggling to pinpoint the root cause. export interface Days { name:string; } @Compon ...

Tips for resolving the ExtPay TypeError when using Typscript and Webpack Bundle

I am currently trying to install ExtPay, a payment library for Chrome Extension, from the following link: https://github.com/Glench/ExtPay. I followed the instructions up until step 3 which involved adding ExtPay to background.js. However, I encountered an ...

In order to determine if components linked from anchor elements are visible on the screen in Next.js, a thorough examination of the components

Currently, I am in the process of developing my own single-page website using Next.js and Typescript. The site consists of two sections: one (component 1) displaying my name and three anchor elements with a 'sticky' setting for easy navigation, a ...

The copy to clipboard feature is malfunctioning when used with a hidden input field in a React application

To implement the copy to clipboard feature, I have successfully achieved it by using the button type as text with type="text". However, the functionality does not work when the button type is set to hidden. Here is the link to the code on CodeSandbox: htt ...

Issues with jQuery fundamentals

For a while now, I've been grappling with jQuery. It's undeniably powerful and offers a plethora of fantastic capabilities. However, my struggle lies in the fact that I tend to incorporate multiple jQuery features simultaneously. For example, on ...

The synchronized block is missing the "children" property during retrieval

Recently, the Notion API introduced support for synced_block functionality. I have been utilizing this feature in combination with Next.js. Based on the information provided in the documentation and the changelog, the expected output should include specifi ...