Is it possible to access headers and the request context from the loader?
I want to access the value of some request headers so I can use them in the loader. What is the best way to do so?
(the equivalent in Next.js is this: https://nextjs.org/docs/app/api-reference/functions/headers)
2 Replies
stormy-gold•4mo ago
Loaders are isomorphic, so after the initial request to the site, they run on the client. This means you can’t access request headers directly in client-side code. To access headers, you need to create a server function using createServerFn, and use getHeaders() inside that function.
import { createServerFn } from '@tanstack/react-start'
import { getHeaders } from '@tanstack/react-start/server'
export const getServerTime = createServerFn({ method: 'GET' }).handler(
async () => {
console.log(getHeaders())
// {
// "accept": "/",
// "accept-encoding": "gzip, deflate, br",
// "accept-language": "en-US,en;q=0.9",
// "connection": "keep-alive",
// "host": "localhost:3000",
// ...
// }
},
)
foreign-sapphireOP•4mo ago
Thanks a lot AMIR! Got it!