I have a function myFetch which is a wrapper around fetch to add a token
in the headerimport 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 get an error when calling this function on the 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 to "import {cookies} only from 'next/headers'" server side
You can conditionally import each module based on the current type of the window object. If undefined; import server module, if not client module:
const myFetch = async (...args) => { let token; if (typeof window === "undefined") { const { default: clientCookies } = await import("js-cookie"); token = clientCookies.get("authToken"); } else { const { cookies: serverCookies } = await import("next/headers"); token = serverCookies().get("authToken").value; } args[1].headers = { Authorization: `bearer ${token}` }; const res = await fetch(...args); const data = await res.json(); return data; };