admin管理员组

文章数量:1122832

I am trying to set the cookies in the browser Application. I get the cookies values from the response of the API's headers as set-cookie. This is the value:

'set-cookie': 'sessionid=<REDACTED>; expires=Sun, 22 Nov 2025 04:02:33 GMT; HttpOnly; Max-Age=31536000; Path=/, expires=Sat, 04 Nov 2024 04:02:33 GMT; HttpOnly; Max-Age=5453453; Path=/',

Here is the page calling the API on the server side.

import { getMainData } from "@/api/server";

export default async function Home() {
  const response = await getMainData();

  return (
    <div>
      Home Data
    </div>
  );
}

This is the API function.

import { BASE_URL } from "@/lib/constants";
export async function getMainData() {
  try {
    const _res = await fetch(`${BASE_URL}/main/data/`, {
      method: "GET",
      credentials: "include",
      mode: "cors",
    });

    console.log("_res", _res);

    const _data = await _res.json();

    return {
      response: _data,
    };
  } catch (error) {
    return {
      response: error,
    };
  }
}

Kindly give the solution to set the cookies in the browser.

I am trying to set the cookies in the browser Application. I get the cookies values from the response of the API's headers as set-cookie. This is the value:

'set-cookie': 'sessionid=<REDACTED>; expires=Sun, 22 Nov 2025 04:02:33 GMT; HttpOnly; Max-Age=31536000; Path=/, expires=Sat, 04 Nov 2024 04:02:33 GMT; HttpOnly; Max-Age=5453453; Path=/',

Here is the page calling the API on the server side.

import { getMainData } from "@/api/server";

export default async function Home() {
  const response = await getMainData();

  return (
    <div>
      Home Data
    </div>
  );
}

This is the API function.

import { BASE_URL } from "@/lib/constants";
export async function getMainData() {
  try {
    const _res = await fetch(`${BASE_URL}/main/data/`, {
      method: "GET",
      credentials: "include",
      mode: "cors",
    });

    console.log("_res", _res);

    const _data = await _res.json();

    return {
      response: _data,
    };
  } catch (error) {
    return {
      response: error,
    };
  }
}

Kindly give the solution to set the cookies in the browser.

Share Improve this question edited Nov 25, 2024 at 7:45 eternal_white 4804 silver badges14 bronze badges asked Nov 23, 2024 at 4:10 JohnJohn 3231 gold badge3 silver badges10 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

you can import cookie like this

import { cookies } from "next/headers";

and after that you should use set method from cookie which you have imported from next/headers like this :

cookies().set('name of token', yourtoken ,  { httpOnly: true })

and then return your token

本文标签: javascriptSet Cookie of API Headers Response in browser cookies in App router in nextjs 14Stack Overflow