TanStackT
TanStack11mo ago
5 replies
uncertain-scarlet

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:
ERROR  ../../node_modules/.pnpm/@tanstack+start-server-core@1.114.23/node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js (2:9): "Readable" is not exported by "__vite-browser-external", imported by "../../node_modules/.pnpm/@tanstack+start-server-core@1.114.23/node_modules/@tanstack/start-server-core/dist/esm/transformStreamWithRouter.js".
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

3/18/25, 2:11 PM

Was this page helpful?