how to set header on the server
Unanswered
Oriental Greenfinch posted this in #help-forum
Oriental GreenfinchOP
basically I have some value in my localStorage that is created at login time, I need to attach this value from localstorage as header to request on server side, how to do that?
16 Replies
can't you just set a cookie at login time or is it restricted from your auth library?
Oriental GreenfinchOP
i think i can do that, i set it by using cookies().set?
yep
that way you should be able to get the data server-side at anytime
Oriental GreenfinchOP
somehow i managed to do that, but i am getting some nasty loop
i have such wrapper
and it will run fetchData in a loop
const SessionLoader = ({ children }: { children: React.ReactNode }) => {
const session = useSession();
if (session.status === "loading") {
return <div className="loading" />;
}
if (session.status === "authenticated" && session.data.accessToken) {
setCookie("token", session.data.accessToken);
}
return <>{children}</>;
};export async function setCookie(name: string, value: string) {
cookies().set(name, value);
}async function fetchData(): Promise<File[]> {
return await api.get("directories", {
headers: {
"X-Company-ID": cookies().get("X-Company-ID")?.value,
Authorization: cookies().get("token")?.value,
},
});
}and it will run fetchData in a loop
well ofcourse, that setCookie needs to be in a useEffect so that it doesn't run every rerender....
Oriental GreenfinchOP
i commented setCookie for now and apparently cookies().get.. is the problem
idk how is it possible when i have both headers i got
Maximum call stack size exceeded but with one header it worksare you sure its not because calling setCookie() not in a
useEffect() causes SessionLoader to rerender and calls setCookie() againOriental GreenfinchOP
nah, i commented all setCookie
literally when i comment either
Authorization or X-Company-ID it worksit actually works when i do
api.get(..).then(({data}) => data)thank you for help
allright, glad it worked out
Oriental GreenfinchOP
i hope this topic will help someone in the future with same problem