TanStackT
TanStack4mo ago
11 replies
slow-yellow

TanStack Start SSR + Cookie Auth Issue - Need Advice

Hi! I'm facing an SSR authentication issue with TanStack Start and would love some feedback on my solution.

The Problem

I'm using TanStack Start with cookie-based authentication. Client-side navigation works perfectly, but SSR fails because server-side requests don't include browser cookies.
Working: Client navigation (cookies auto-included)
Broken: Hard refresh/direct URLs (SSR can't access cookies)

// This fails during SSR
export const Route = createFileRoute("/__root")({
  beforeLoad: async ({ context }) => {
    // :x: No cookies available here
    await context.queryClient.ensureQueryData(meOptions());
  },
});

My Proposed Solution

Using createIsomorphicFn.

// isomorphic-client.ts
import { createIsomorphicFn } from "@tanstack/start";
import { getHeaders } from "@tanstack/start/server";
import { Api } from "./api-gen"; // swagger-typescript-api

const getServerHeaders = createIsomorphicFn()
  .client(() => ({}))
  .server(() => {
    const headers = getHeaders();
    return headers.cookie ? { Cookie: headers.cookie } : {};
  });

export const apiClient = createIsomorphicFn()
  .client(() => {
    return new Api({
      baseUrl: import.meta.env.VITE_BASE_API_URL + "/api/user",
      baseApiParams: { credentials: "include" },
    });
  })
  .server(() => {
    const serverHeaders = getServerHeaders();
    return new Api({
      baseUrl: process.env.VITE_BASE_API_URL + "/api/user",
      baseApiParams: {
        credentials: "include",
        headers: { ...serverHeaders }, // Forward cookies
      },
    });
  })();

Then just change imports in my fetchers:
// Before
import { apiClient } from "../api/api-client";
// After
import { apiClient } from "../api/isomorphic-client";

Questions

1. Is this the right approach for TanStack Start SSR + cookies?
2. Any gotchas I should be aware of with this solution?
3. Better alternatives? (I need to keep swagger-typescript-api and httpOnly cookies)
Was this page helpful?