javascriptcookiesnext.jsserver-side-rendering

Next.js 13 how to fetch cookie on client side and server side


I have a function myFetch which is a wrapper for fetch to add token in the header

import clientCookies from "js-cookie";
import {cookies} from "next/headers";

const myFetch = async (...args) => {
let token
if (typeof window === "undefined") {
  // client side
  token = clientCookies.get("authToken")
} else {
  // server side
  serverCookies = cookies()
  token = serverCookies.get("authToken").value
}

args[1].headers = {"Authorization": `bearer ${token}`}
const res = await fetch(...args)
const data = await res.json()
return data
}

But I am receiving error when calling this function client side

You're importing a component that needs next/headers. That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component.
Learn more: https://nextjs.org/docs/getting-started/react-essentials

Is there any way I can "import {cookies} from 'next/headers'" server side only


Solution

  • You can conditionally import each module based on the current type of the window object. If it is undefined; Import the server module, if not the client module:

    const myFetch = async (...args) => {
      let token;
      if (typeof window === "undefined") {
        const { cookies: serverCookies } = await import("next/headers");
        token = serverCookies().get("authToken").value;
      } else {
        const { default: clientCookies } = await import("js-cookie");
        token = clientCookies.get("authToken");
      }
    
      args[1].headers = { Authorization: `bearer ${token}` };
      const res = await fetch(...args);
      const data = await res.json();
      return data;
    };