T
TanStack8mo ago
fascinating-indigo

How to read request object for a route?

Hello, I was wondering what is the correct approach for reading the request object for a route? In react router you would do something like:
import { LoaderFunctionArgs, redirect } from 'react-router';
import { parse } from 'cookie';

export async function loader({ request }: LoaderFunctionArgs) {
const cookie = request.headers.get('cookie');

const accessToken = parse(cookie || '').accessToken;

if (!accessToken) {
return redirect('/login/email');
}

return redirect('/profile');
}
import { LoaderFunctionArgs, redirect } from 'react-router';
import { parse } from 'cookie';

export async function loader({ request }: LoaderFunctionArgs) {
const cookie = request.headers.get('cookie');

const accessToken = parse(cookie || '').accessToken;

if (!accessToken) {
return redirect('/login/email');
}

return redirect('/profile');
}
Whats the equivalent of this in tanstack router? I scoured the documentation but couldnt find a resource on how exactly I can read the request object.
6 Replies
fair-rose
fair-rose8mo ago
are you using router or start?
fascinating-indigo
fascinating-indigoOP8mo ago
@Manuel Schiller I was aiming to use start - I'm used to having access to SSR so I figured start is better in this case. I make use of the request object very heavily in my past RR apps, so I figured going this route might help with the migration to tanstack. Though, I'm open to hearing your suggestions on what would be the best approach. I did see that the official TSR examples point to handling auth client-side through context, though I'm not sure I'm fully ready to try that approach at the moment
fair-rose
fair-rose8mo ago
the loader is executed on the client in router, and on the server with start and ssr
fair-rose
fair-rose8mo ago
Server Functions | TanStack Start React Docs
What are Server Functions? Server functions allow you to specify logic that can be invoked almost anywhere (even the client), but run only on the server. In fact, they are not so different from an API...
fascinating-indigo
fascinating-indigoOP8mo ago
This is super interesting. So if I'm reading it correctly, I can define it in the route file, have it check auth cookie, and then call it at the beginning of the loader to trigger the check. Neat! thanks
fair-rose
fair-rose8mo ago
make sure to call it only from a serverfunction as it won't work on the client side

Did you find this page helpful?