One of the functionalities in my code is a custom function called myFetch, which serves as a wrapper for fetch to include a token in the header.
import clientCookies from "js-cookie";
import {cookies} from "next/headers";
const myFetchedData = async (...args) => {
let token
if (typeof window === "undefined") {
// When running on the client side
token = clientCookies.get("authToken")
} else {
// When running on the server side
serverCookies = cookies()
token = serverCookies.get("authToken").value
}
args[1].headers = {"Authorization": `bearer ${token}`}
const response = await fetch(...args)
const information = await response.json()
return information
}
However, I encountered an error when using this function on the client side.
You're trying to import a component that requires next/headers, which only functions within a Server Component. But one of its parent components is assigned with "use client", making it a Client Component.
For more information, visit: https://nextjs.org/docs/getting-started/react-essentials
I am seeking guidance on how to specifically "import {cookies} from 'next/headers'" exclusively for server-side purposes.