javascriptnext.jsserver-side-rendering

Next.js server side component request, how to send my cookie token?


My Next.js is 14.1.0 and I'm using App router.

async function Page() {
  const dataPromise: Promise<any> = getData();
  const data = await dataPromise;
  console.log('data: ', data);
  return (
    ....
  );
}

getData is a simple function which I make a request to the Django rest API. If there is a token in the cookie, requests can be made to protected services.

When I make the same request on the client side, the response is 200 (OK) because I have a token. However, when I make a request on the server side, I get a 401 (Unauthorized) error.

I guess the server side does not see my token when I make a request. How can I solve this problem? How do I use my token for server side fetching?


Solution

  • When you make a request from the browser to get the page, your cookies are sent along. You can grab your token using the cookies() function of Next.js and pass it to getData inside which you set the Authorization header:

    import { cookies } from "next/headers";
    
    export default async function Page() {
      const cookieStore = cookies();
      const accessToken = cookieStore.get("access_token");
      const data = await getData(accessToken);
      return "....";
    }
    

    The Cookies.get('access_token') you said you are using in the comments is I guess working with browser APIs and not looking inside HTTP headers.