Accessing cookies in `loader`
I asked this question on twitter earlier today (https://x.com/radek_1313/status/1901999925858087293?s=46)
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:
Radek Skrabucha (@radek_1313) on X
Hey @tannerlinsley is there a way to read cookies in beforeLoad and loader? When on dev Iām using getCookie from @tanstack/react-start/server and it works fine, however the build step crushes š¤
X
2 Replies
foreign-sapphireā¢6mo ago
so you want to read the cookie on either server or client?
then you need two different implementations
the client one would read the document cookies and the server one would use getCookie
both implementations need to be combined via createIsomorphicFn
sensitive-blueOPā¢6mo ago
okay I got it, now works perfectly! Thank you so much @Manuel Schiller š