Getting Cookies (Raw Request) from Page Request in Loader / BeforeLoad #3649
-
I have a use case where my SSR server is not my primary API server and I need to proxy requests to another server for data that the route needs. In order to do that, I need to grab the auth cookies from the page request, set them on the proxied API request and then return that data from the loader. Is this something that is available inside of loaders? I don't see any APIs that I can use and have tried using some of the tanstack start methods like export const Route = createFileRoute('/org/$slug/onboarding')({
beforeLoad: async ({ context }) => {
const request = getWebRequest();
const cookie = getCookie(INTERMEDIATE_SESSION_TOKEN_COOKIE_NAME);
// These are empty
console.log(`request from beforeLoad: ${request}`);
console.log(`cookie from beforeLoad: ${cookie}`);
const data = { pathname: location.pathname };
return await requireAuth({ data });
},
loader: async () => {
const request = getWebRequest();
const cookie = getCookie(INTERMEDIATE_SESSION_TOKEN_COOKIE_NAME);
// These are empty
console.log(`request from loader: ${request}`);
console.log(`cookie from loader: ${cookie}`);
},
component: RouteComponent,
}); In NextJS15 which I am gleefully migrating away from there were hooks to be able to load cookies from the page request inside of react server components. i.e. something like this: import { cookies } from 'next/headers';
export const simpleApiMutation = async (
endpoint: string,
body: Record<string, unknown> = {},
returnResponse: boolean = false
): Promise<any> => {
// Retrieve cookies from Next.js headers
const cookieStore = await cookies();
console.log(`[POST]: ${endpoint}`);
// Make the POST request
const response = await fetch(endpoint, {
method: 'POST',
headers: {
Cookie: cookieStore.toString(),
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
// Optionally return the raw Response object
if (returnResponse) {
return response;
}
// Parse the response as JSON
const json = await response.json();
// If the response was not OK, throw an error
if (!response.ok) {
throw new Error(json.message || 'Request failed');
}
return json;
}; Thanks, enjoying TSR/TSS so far and finding my development speed pick back up again after migrating away from next |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
you cant run |
Beta Was this translation helpful? Give feedback.
you cant run
getWebRequest()
inbeforeLoad
orloader
as those methods run on both the client and the server.if you need them run only on the server, wrap the logic into a server function. inside the server function you can then call
getWebRequest()