Accessing cookies in `loader`
I'm storing my bearer token in cookie so that it can be accessible both on client and server.
1. beforeLoad
With
beforeLoad what I want to do is check if the cookie is there, decode the JWT token and check if it's fresh. Based on this I either redirect user to /sign-in page or do nothing (let user go to protected route).For context I have util
const isBrowser = typeof window !== 'undefined' to check whether it works in browser or server.At first when I went to route with browser router - I click a Link it works fine. But when I went directly to protected route with URL the beforeLoad function didn't work.
So I added this:
const token = isBrowser ? authTokenStorage.get() : getCookie(AUTH_TOKEN_KEY) and getCookie comes from import { getCookie } from '@tanstack/react-start/server'.In development mode it works as expected, when user goes to protected route, directly or with Link and router, it does redirect user to
/sign-in page.However when I try to build the app it gets error and crashes.
2. loader
Same story here, I want to access the Cookie with bearer token so that I can prefetch some data with Tanstack Query.
As far as I understand the loader works on server. In development mode it works as expected, when building error.
I know that we can access cookies in server function, but is there some way to access them directly in
beforeLoad and loader? The getCookie works fine only in development.For context this is the build error:
X
•3/18/25, 2:11 PM