skip to Main Content

I use nextjs 14. In the dashboard root of the layout file, which is a server component, I make a get request to the api developed with .net.
The root of the problem is that the cookies set by .net in my browser are not sent to the api side so that the information corresponding to the same cookie is sent to me.
But this problem did not exist in client components, for example, when using useEffect.
In addition, I have access to cookies in the components server and I can set and send it in the header of my get request. But with this method, api does not give me a proper answer.
How can I solve the problem?
Any advice is a great help

my code:

import { myAxios } from "src/utils/axios";

const DashboardLayout = ({ children }) => {
  myAxios("apiacount/state")
    .then((res) => {
      console.log("ok");
    })
    .catch((err) => {
      console.log("not ok");
      // console not ok Because cookie not send to api in server component
      // Unlike the client component
    });

  return <p>test</p>;
};

export default DashboardLayout;

I expect the cookies to be sent to the external api in the server component

2

Answers


  1. Can you provide your code? Please remember that server components cannot access the cookie. If you want to use and send a cookie to the API from the browser (cookies are always stored here), you must use the client component. You can break your component into smaller parts for your situation and use client-side components.

    or another approach is (in server side component’s) =>

    import { cookies } from "next/headers";
    
    const myCookie = cookies().get("cookieName").value;
    

    Then, put this in your API call.

    –!! Notice: If it has the httpOnly flag, you can’t access it through JavaScript !!–"

    Login or Signup to reply.
  2. If your API supports session or token authentication, you can consider using session or token authentication. In this case, you need to acquire the token on the browser side and add it to the authorization header of each request. This can usually be achieved by performing this operation in a client-side component .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search