I must retrieve cookies from the GET call API within the route.js file

I've developed a website using Next.js 13 with a route called /api/users/me. In this route, I need to access the cookies to extract the token. While calling the API from the browser gives me the desired result, trying to call it from the frontend page returns null for the cookies.

In src/api/users/me/route.js

import { NextResponse, NextRequest } from "next/server";
import { connectDB } from "@/dbConfig/dbConfig";

connectDB();

export async function GET(request) {

  try {

    console.log("Token is: ", request.cookies); // Expecting to receive cookies but get null
    return NextResponse.json({ msg: "success" }, { status: 200 });
  } catch (error) {
    return NextResponse.json(
      { msg: "can't get data", err: error.message },
      { status: 500 }
    );
  }
}

In src/app/profile/page.jsx

import UserDetails from "@/components/UserDetails";
import { cookies } from "next/headers";

async function getData() {
  const cookieStore = cookies();
  const token = cookieStore.get("token"); // Able to retrieve the cookies here
  try {
    console.log(token.value);
    const res = await fetch(`http://localhost:3000/api/users/me`, {
      headers: {
        userToken: String(token.value), // Trying to pass it in the headers
      },
    });
    if (!res.ok) {
      throw new Error("Failed to fetch data, please try another time");
    }

    return res.json();
  } catch (error) {
    console.log("Error loading topic", error);
      }
}

async function ProfilePage() {
  const data = await getData();

  return (
    <div className="flex flex-col justify-center items-center min-h-screen">
      <h1 className="font-bold text-3xl">Profile page</h1>
      <p className="text-gray-600">This is the profile page</p>
      <UserDetails />
    </div>
  );
}

export default ProfilePage;

Answer №1

Your API route is not valid. Please ensure that your API routes are defined in the route.js file.

To resolve this, move your src/api/users/me.js to src/app/api/users/me/route.js

If you need help with handling cookies, refer to this documentation - https://nextjs.org/docs/app/building-your-application/routing/router-handlers#dynamic-functions

import { cookies } from 'next/headers'
 
export async function GET(request: Request) {
  const cookieStore = cookies()
  const token = cookieStore.get('token')
 
  return new Response('Hello, Next.js!', {
    status: 200,
    headers: { 'Set-Cookie': `token=${token.value}` },
  })
}

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

Inconsistencies observed during the native JSON import process in JavaScript

Encountered a strange behavior when loading a JSON file into JavaScript while working on a React project. Seeking an explanation and guidance on properly accessing data from the JSON data store. The JSON file contains product data: { "product ...

What could be causing my HTML5 page to crash when accessed online, but not when viewed locally?

I am just getting started with HTML5 and decided to experiment with canvas. This is the first canvas page I have created. Everything works fine when I run the page locally (i.e. file:///), but once I upload the files to my webhost, the page gets stuck whi ...

BrowserSync Failing to Load

Recently started using BrowserSync and I'm trying to figure out how to make it work smoothly. My main file that contains all the code is named 'gulpwork'. Inside 'gulpwork', there are 4 folders - two for converting Pug from &apos ...

Working with an array of object in Vuex for form handling

Looking to make updates to a vuex store that includes an array of objects: Users have a combobox for making selections, which then updates a property of the object in the database. However, every time I choose an item from the autocomplete (combobox) I e ...

Guide on extracting URLs from an XML sitemap URL by utilizing PHP

<?php function retrieveURLsFromSitemap($sitemapUrl) { $xml = simplexml_load_file($sitemapUrl); if ($xml === false) { die('Error loading XML'); } $urls = []; foreach ($xml->url as $url) { $urls[] = (str ...

What is the best way to push a variable after employing the split function in JavaScript?

error: An unexpected TypeError occurred while trying to read property 'push'. The error was on this line: " this.name[i].push(arrayData[0]); " I'm confused because the console.log statement before that line shows "data is loaded:" alo ...

Utilize linear gradient effect in editing images and then convert them to base64 format using React

I have been working with the "canvas" library to edit an image via URL using linear-gradient, employing various methods. However, I am facing challenges in achieving the desired results so far. The methods I tried using canvas do not seem to work seamless ...

Steps for displaying an HTML table in Excel by clicking on a button

My goal is to open an HTML table in XLS format with a single click of a button. Currently, I have a JavaScript function that allows me to export the HTML table to XLS using the "save as" option. However, I want to enhance this functionality so that clickin ...

Postman is showing an error when making a request using Express.js app.get()

Recently, I started working with Express.js and I am using Postman to test my API. When running the code below, I successfully retrieve all members from the object: // gets all members app.get('/api/members', (req, res) => { res.json(membe ...

"Combining AJAX and PHP for tic-tac-toe game is providing a solution for the following query

Currently, I am in the process of developing a tic tac toe game that involves the use of Ajax and Php, both of which are relatively new to me. While I have researched various discussions on this topic, I haven't been able to find a solution to my spec ...

Error: The property 'case sensitive routing' cannot be accessed because it is undefined

Task at hand: Running ExpressJS port using Node.js, nodemon, and lib. Operating System: Windows 10 Home x64 Node.JS Version: Lts The Challenge: Getting the ExpressJS port to run successfully. Current Issue: Encountering an internal file error, potentiall ...

Can WebSocket messages be encoded?

Is there a way to encrypt or obscure the data I transmit via websockets? For example, the message looks like this: var encryptedMsg = { type: "message", data: { message: "Hello world!" } } I require the ability to send this message in ...

Having trouble figuring out how to update a list using ajax in Yii

I need to modify a JavaScript function that filters the content of a list. The current code looks like this: var id = $(this).data('id'); $.fn.yiiListView.update('contests-list', { data: {category: 2} }); I couldn't find any ...

Sending JSON data results

I received this JSON response: {"data":[{"series":{"id":"15404","series_code":"TOS","publisher_id":"280","series_short_name":"Tales of Suspense","start_year":"1959","end_year":"1968","published":"1959-1968","type_id":"1","no_issues":"99","published_ ...

The getStaticProps function in Next.js does not retrieve any specified data

I am encountering an issue while trying to fetch single data by ID using getStaticPaths and getStaticProps. I keep getting the error message that data is not defined. Can anyone please point out where I might be making a mistake? Below is my code from the ...

I am encountering TypeError issues while attempting to mock/test Vuex store modules

I'm currently in the process of learning how to effectively test components and JavaScript code, but I have hit a roadblock with Vuex modules. Below is the code snippet for the test: import { shallowMount } from '@vue/test-utils' import Wor ...

Troubleshooting Mongoose and MongoDb Connectivity Issues

Previously, I had no trouble connecting to Atlas from my home wifi, but I encountered issues at Starbucks. After switching to google fiber, I am now facing this error. at Pool.<anonymous> (/Users/j/Desktop/projects/templateApp/node_modules/mong ...

Correlating Mailgun Webhook event with Mailing list email

Recently, I have started using the Mailgun API to send emails and have also begun utilizing their mailing list feature. When sending to a mailing list, such as [email protected], I receive a single message ID. However, when receiving webhook responses, t ...

Is it possible to translate the content of the page into English and French simply by clicking on the designated buttons?

As I dive into working with knockout, I am still in the learning process. Currently, I have a dropdown code where selecting English translates the entire page to English and selecting French translates it to French without any issue. I believe this functio ...

Unable to invoke angular ng-click function using jQuery

Can someone assist me in calling ng-click from jQuery correctly? I am having trouble getting it to work. Any guidance on the proper way to do this would be greatly appreciated. HTML: <a ng-click="changeData()">Testing</a> <a ng-click="chan ...