Next.js 13 How to get cookies on client and server side
P粉690200856
P粉690200856 2024-04-01 11:22:43
0
1
679

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粉690200856
P粉690200856

reply all(1)
P粉470645222

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;
};
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!