Is there a better way to pass cookies from RSC to Route Handler?
Answered
Golden-cheeked Warbler posted this in #help-forum
Golden-cheeked WarblerOP
Hi, I have a server component that will fetch current user from a route handler, and pass the result to a client component. Is there a way I can automatically pass the cookie to my getCurrentUser endpoint, or is there a better way completely to do this? Maybe I could use server actions instead of and route handler?
import { cookies } from "next/headers";
import { Auth } from "../auth";
export const Header = async () => {
const token = cookies().get("token");
let user: User | null = null;
if (token) {
const res = await fetch("http://localhost:3000/api/auth/getCurrentUser", {
headers: { Cookie: `${token.name}=${token.value}` },
});
if (res) user = await res.json();
}
return (
<div className="flex w-full items-center justify-between rounded-lg bg-black p-2 text-white">
Acme
<Auth user={user ?? undefined} />
</div>
);
};Answered by Golden-cheeked Warbler
found you can just pass all headers directly:
import { headers } from "next/headers";
import { Auth } from "../auth";
export const Header = async () => {
let user: User | null = null;
const res = await fetch("http://localhost:3000/api/auth/getCurrentUser", {
headers: headers(),
});
if (res) user = await res.json();
return (
<div className="flex w-full items-center justify-between rounded-lg bg-black p-2 text-white">
Acme
<Auth user={user ?? undefined} />
</div>
);
};1 Reply
Golden-cheeked WarblerOP
found you can just pass all headers directly:
import { headers } from "next/headers";
import { Auth } from "../auth";
export const Header = async () => {
let user: User | null = null;
const res = await fetch("http://localhost:3000/api/auth/getCurrentUser", {
headers: headers(),
});
if (res) user = await res.json();
return (
<div className="flex w-full items-center justify-between rounded-lg bg-black p-2 text-white">
Acme
<Auth user={user ?? undefined} />
</div>
);
};Answer