Having trouble saving a JSON object as a cookie in Next.js using js-cookie

I am having trouble setting user data along with a token ID in a Cookie. The token is set correctly and appears in the console.log output, but my user JSON object is not being properly set and only shows as "object Object" in the Cookies. However, I can see my user data in the console.log. It seems like I am unable to convert JSON data into a cookie. Below is my code using Next.js and the packages I am utilizing for this task.

Packages Used:

  1. js-cookies
  2. Next.js - latest version

This is my API for user login:

import db from "../../helpers/initDB";
import User from "../../models/User";
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'

db.connect();

// eslint-disable-next-line import/no-anonymous-default-export
export default async (req,res)=>{
 const {email,password} = req.body
 try{
    if(!email || !password){
      return res.status(422).json({error:"All Fields Are Required"})
    }
  const user = await User.findOne({email})
  if(!user){
      return res.status(404).json({error:"User does not exist with that email"})
  }
    const doMatch =  await bcrypt.compare(password,user.password)
    if(doMatch){
       const token =  jwt.sign({userId:user._id},process.env.JWT_SECRET,{
            expiresIn:"7d"
        })
        const {name,role,email} = user
        res.status(201).json({token,user:{name,role,email}})
    }else{
       return res.status(401).json({error:"Email or password do not match"})
    }
 }catch(err){
     console.log(err)
 }
}

db.disconnect();

My API is functioning correctly and returning the response status with all the necessary data.

Here is the part of the code where I am attempting to set the cookie:

console.log(res2)
  Cookie.set('user', res2.user);
  Cookie.set('token', res2.token);
  router.push('/dashboard/')

And here is the console.log output showing the user data and token:

Object { token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2MWE4YzcwMGIxZmI3OWJmOGNjOWY3ZjUiLCJpYXQiOjE2Mzg1MTczODIsImV4cCI6MTYzOTEyMjE4Mn0.9T-B4c3xtsgCSGSWUMCZ_GU56FYC5VLeVDhGzAWiwjA", user: {…} }

User: Object { name: "mohit nagar", role: "user", email: "[email protected]" }

And here are the cookies:

{ "Request Cookies": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2MWE4YzcwMGIxZmI3OWJmOGNjOWY3ZjUiLCJpYXQiOjE2Mzg1MTY1NzcsImV4cCI6MTYzOTEyMTM3N30.PoBD03Qp-7-iN5yvnjvQfflTI5DO8z3Lqk3sMYZs0Y0", "user": "[object Object]" } }

I'm unsure about what I might be doing wrong in this process.

Answer №1

It is important to note that the value of a cookie must always be a string. To achieve this, you can convert your user object into JSON by using the stringify method.

Here's an example of how you can set a cookie with the user data:

Cookie.set('user', JSON.stringify(res2.user))

When you need to retrieve the information stored in the cookie, you will have to parse the string back into an object:

const user = JSON.parse(Cookie.get('user'))

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

Defining JSON Schema for an array containing tuples

Any assistance is greatly appreciated. I'm a newcomer to JSON and JSON schema. I attempted to create a JSON schema for an array of tuples but it's not validating multiple records like a loop for all similar types of tuples. Below is a JSON sampl ...

Converting a text file to JSON format using Adobe Acrobat: A tutorial on proper referencing

I am facing an issue with converting a string from a file attached to my PDF (JSONTEST.txt) into JSON format so that I can reference it using obj[key]. Despite trying to use eval(), I encounter the following error every time: SyntaxError: missing ; before ...

JavaScript seems to have difficulty correctly parsing objects from JSON

Having trouble populating a Repeat Box with objects from a JSON document. Despite my efforts, it keeps duplicating the first item instead of adding each one individually. Any ideas on what might be causing this issue? Below is the code I am currently usin ...

Utilizing getStaticProps for Performance Optimization in Next.js

I am currently in the process of setting up a blog using Next.js and GraphCMS. I have an ArticleList component that I want to display on multiple pages, such as my homepage and under each article as a recommendation. Since the article list is sourced from ...

Angular $resource encounters a 400 Bad Request error when attempting a PUT request, triggering the $resolve and $promise

My service is structured as follows (with variables removed): angular .module('app') .factory('Employee', function($resource) { return $resource("https://api.mongolab.com/api/1/databases/:dbName/collections/:collectionN ...

Is it possible to transfer a URLFetchApp.fetch request from the Google Apps Script side to the JavaScript side?

My current task involves parsing an XML document tree upon clicking a button. The XML file is obtained using a lookup function that requires two values ("id" and "shipping") to be inserted into the appropriate URL. Then, the data retrieved is parsed using ...

No data is being recorded in the Firestore database

This component in nextjs is designed to write data to a firestore database after the user clicks a button. Unfortunately, Firebase seems to be having trouble writing the data, even though the alert message following the supposed data dump is successful. I ...

Sorting JSON data in EJS based on categories

Hello, I am facing a dilemma. I need to apply category filtering to a JSON file but I am unsure of how to proceed with it. For instance, I wish to filter the 'vida' category along with its description and price. I seem to be stuck at this junctu ...

Utilizing Weather APIs to fetch JSON data

Trying to integrate with the Open Weather API: Check out this snippet of javascript code: $(document).ready(function() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { $(".ok").html("latitude: " + ...

Ways to dynamically fetch data by merging the response outcome with a dynamic parameter from the route in Vue.js

For the first time, I have been tasked with dynamically retrieving object parameters from the URL parameter. I am aware that I can use this.$route.params.[somelink-parameter] to obtain the URL parameter, and I understand how to retrieve and store the respo ...

When using JSON.stringify on a map object, it returns an empty result

var map1= new Map(); map1.set("one",1); var map2 = new Map(); map2.set("two",2); concatMap = {}; concatMap['one']= map1; concatMap['two']= map2; JSON.stringify(concatMap); //outputs : "{"one":{},"two":{}}" I als ...

Is there a way to run /_next/static/xxx.js using a script tag?

I have customized my next.config file (webpack) to generate a static JavaScript file (.next/static/loader.js). The original loader.js is an Immediately Invoked Function Expression (IIFE): (function stickerLoader(){ alert('Hello'); // ... so ...

Encountering a CORS issue specifically on the client side of a Next.js application when interacting with an API gateway

I've been struggling with this issue for a week now and can't seem to fully describe it. I have a FastAPI server running as a Lambda connected to API Gateway. https://i.stack.imgur.com/S5Zx9.png Both FastAPI and API Gateway have CORS enabled, b ...

Can JSON.parse be used on only a portion of an object in JavaScript?

Currently, I am facing an issue with a lengthy JSON file that I am fetching from a URL using https.request. Upon attempting to parse the string with JSON.parse, I encounter an "Unexpected end of JSON input" error. It appears that there is a limit to the ...

A basic structure for a JSON array

Perhaps my next question may appear silly, but I'll ask it anyway :) Here is the structure in question: { "name": "Erjet Malaj", "first_name": "Erjet", "work": [ { "employer": { "id": "110108059015688 ...

Tips on converting Django model into desired format for Bootstrap-tables plugin integration

I want to integrate the bootstrap-table plugin with server-side functionality using Django Rest Framework to populate the data on the table. However, I keep getting the message "No matching records found". After some investigation, I discovered that a spec ...

The filtering feature for array and model selection in Angular's UI-Select appears to be malfunctioning

Below is a Json structure: $scope.people = [ { name: 'Niraj'}, { name: 'Shivam'}, { name: 'Arun'}, { name: 'Mohit'}] There's also a variable, var array = "Niraj,Shivam";. My goal is to filter out the names fro ...

Show only specific data from JSON results

I am trying to display a specific cryptocurrency's price without the need for curly braces or explicitly stating "USD". Currently, it appears as {"USD":0.4823} when using the following code: <script> $(document).ready(function () { ...

Can anyone suggest a method for adding comments and improving the organization of a bower.json file?

Managing a large project with numerous bower dependencies can be challenging. It's often unclear whether these dependencies are still being used or if the specified versions are necessary for a reason. It would be ideal to have the ability to add comm ...

Display a sublist when a list item is clicked

I am receiving a JSON object in my view that looks like this: $scope.mockData = [ { "folder": "folder1", "reports": [{ "name": "report1" }, { "name": "report2" }, { "name": "report3" }] }, { "folder": "folder2", "reports": [{ "name": ...