I need to figure out how to send an HTTPOnly cookie using a fetch request in Next.js

After finishing a comprehensive guide, I am now working on retrieving user details using a server component. However, even though the browser's cookie is there, it doesn't seem to be showing up in the request.

I decided to customize my profile page and convert it into a server component. However, after refreshing the page to start the fetch request, the token cookie is nowhere to be found. To confirm this, I included the following lines of code within the route handler:

const token = request.cookies.get("token")?.value || "";
console.log(token, "token");

Answer №1

If you're working with NextJS, it's recommended to utilize the cookies-next library https://www.npmjs.com/package/cookies-next

Give this a try:

setCookie('cookie_name', cookie_value, { httpOnly: true })

For fetch requests,

useEffect(() => {
    const setCookie = async () => {
      try {
        const response = await fetch('/api/set-cookie', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ cookieName: 'myCookie', cookieValue: 'cookieValue' })
        });

        if (response.ok) {
          console.log('Cookie set successfully');
        } else {
          console.error('Failed to set cookie');
        }
      } catch (error) {
        console.error('Error setting cookie:', error);
      }
    };

    setCookie();
  }, []);

If you prefer not to use a library:

const [cookies, setCookie] = useCookies(['token']);

  useEffect(() => {
    // Assuming 'token' is retrieved from somewhere
    const token = 'your_token_value';

    // Setting the 'token' cookie with the provided value and options
    setCookie('token', token, {
      httpOnly: true,
    });
  }, []);

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

Utilizing a Function's Return Value as a State in React - A Comprehensive Guide

Currently, I am delving into the realm of functional components within React and have crafted a simple piece of code that should output 'Nah' if the state value is at 0. However, there seems to be an issue as this functionality does not seem to ...

Adding tween.js seems to have caused the button click event to stop triggering

After adding the code line to tween my display box, the click event is no longer triggered. There are no errors in the console. How can I resolve this issue and what might have caused it? createjs.Tween.get(directionsbox, { loop: false }).to({ x:800, y: ...

What's the deal with integrating Supabase sessions into NextJS SSR/SGR?

Is it feasible to integrate Supabase with both server-side and client-side rendering simultaneously? It appears that typically we must opt for one or the other, but NextJS offers the flexibility to define SSG (server-side generated), SSR (server-side rende ...

Can integers be used as keys in a JavaScript object's storage?

Currently, I am in the process of creating a JSON index file to serve as a database index for a javascript application that is currently under development. The structure of my index will resemble the following: { "_id": "acomplex_indice ...

Check out this stylish Twitter-inspired SVG text counter created with a combination of CSS and jQuery! See it in action here: https://jsfiddle.net/moss24

Looking to develop a text counter similar to Twitter that increases the width in green color up to 75%, then switches to yellow until 98%, and finally turns red if the input value is greater than or equal to 400. It should also add a "highlight" class when ...

Providing dynamic string outputs depending on the current date using AngularJS

I set up an advent calendar that reveals a new question every day, but currently the questions aren't showing up. Here's the code I have: The controller located in app.js: .controller('textCtrl', function($http) { this.data = {}; ...

how can I include an AngularJS variable as a parameter in an onclick function?

I attempted to utilize an AngularJS variable as an argument value inside onclick() in order to invoke a JavaScript function. Can someone provide me with instructions on how to achieve this? Here is my code: <div onclick="deleteArrival({{filterList.id} ...

Having trouble with Nextjs API Integration - encountering error 404

I'm currently facing a major issue and I've hit a dead end. I've been spending days trying to connect my local nextjs 14 app to the CVENT API, but I keep receiving a persistent 404 error. Here's what is displayed in the frontend console ...

Enhance JQuery functionality using Typescript

Currently, I am in the process of developing a Typescript plugin that generates a DOM for Header and attaches it to the page. This particular project utilizes JQuery for handling DOM operations. To customize the plugin further, I aim to transmit config Opt ...

Tips for displaying real-time data and potentially selecting alternative options from the dropdown menu

Is there a way to display the currently selected option from a dropdown list, and then have the rest of the options appear when the list is expanded? Currently, my dropdown list only shows the available elements that I can choose from. HTML: < ...

Utilizing Axios: Maintaining session continuity post successful authorization and including it in subsequent requests - testing in a browser-less environment

During this test scenario, I am sending an axios post request to an ExpressJS server that is running with passportjs local. The request includes a userId and password, and the server responds with a status code of 200, along with setting an appropriate hea ...

Troubleshooting: Custom JQuery function not functioning as expected

I am currently facing an issue with the jQuery in my website while trying to implement a portfolio element. It seems to be related to the changePortfolio() function, but I am unsure of how to resolve it. $('.projects a[href^="#"]').on('clic ...

jqGrid is throwing an error: undefined is not recognized as a function

Currently, I am in the process of trying to display a basic grid on the screen. Following the instructions provided in the jqGrid wiki, I have linked and created scripts for the required files. One essential css file, jquery-ui-1.8.18.custom.css, was missi ...

Finding mongoose in an array of objects nested within another object

Here is the MongoDB JSON document I am working with: { categoryId: '1', categoryName: 'Outdoors Equipments', items: [ { itemId: '1', itemName: 'Camping T ...

Choosing specific rows in a kogrid by clicking on a button within a column

My kogrid includes a single column with a view button for each row. I would like to show a popup containing the values of the selected row when the View button is clicked. How can I retrieve the values of the selected row in order to pass them into the p ...

Having trouble with Angular minification not properly updating templates?

As a newcomer to angular development, I am currently working on creating components for AEM 6.2 using angular and utilizing gulp to minify the js files for all the components. In my gulpfile, I have set up the following configuration: var uglify = require ...

What is the best way to make changes to the DOM when the state undergoes a

I've programmed the box container to adjust dynamically based on input changes. For instance, if I entered 1, it will generate one box. However, if I modify the input to 2, it mistakenly creates 3 boxes instead of just 2. import React from 'rea ...

Using Vue along with bootstrap-vue: Ensuring only one list element is expanded in a list (v-for) at any given time

In my Vue project with bootstrap-vue, I am utilizing the b-collapse feature within a v-for loop for lists. While it is functioning correctly, I am struggling to automatically close expanded list elements when a new one is clicked. Here is my question: Ho ...

Error message: JavaScript is unable to save data to an array retrieved from Ajax, resulting in

I am facing an issue with retrieving continuous data from the database using AJAX and storing it in a JavaScript variable. Despite my efforts, I am unable to populate an array with the retrieved values as they always end up being undefined. Below are the s ...

Next.js is currently unable to locate the requested page - Error 404: Page Not Found

Whenever I try to run my app using next dev -p 3001, I encounter a 404 error page not found. In my _app.tsx file: function MyApp({ Component, pageProps }: AppProps) { console.log('pageProps: ', pageProps) return ( <> <Comp ...