search

Home  >  Q&A  >  body text

Next.js 13 How to get cookies on client and server side

I have a function myFetch which is a wrapper around fetch to add a 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 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

P粉690200856P粉690200856266 days ago799

reply all(1)I'll reply

  • P粉470645222

    P粉4706452222024-04-02 00:52:26

    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;
    };
    

    reply
    0
  • Cancelreply