Skip to Content

TanStack Start

Keep the session in an encrypted cookie with TanStack Start, so the server renders the signed-in page first.

Your TanStack Start app renders pages on the server, and you want the first response to show the signed-in page, with no "Checking session…" state and no flash of signed-out content. To do that, the server has to hold the session. In this guide, you keep it in an encrypted cookie: the server signs in, refreshes the tokens before rendering, and sends the signed-in page first.

The browser gets a small client that mirrors the session the server rendered, and the TanStack Router hooks and guards work with it. Server rendering explains how the pieces fit. A complete app is in examples/tanstack-start-ssr.

If your Start app runs in SPA mode, where the browser keeps the session, follow TanStack Start in SPA mode instead.

Before you begin

  • Node.js 22.12 or newer, which TanStack Start needs. See Compatibility for the other versions.
  • A secret of 32 or more random characters to seal the cookie, such as the output of openssl rand -base64 32, set as SESSION_SECRET on the server. vite build doesn't need it. The secret says how to keep and rotate it.
  • The code signs in with DummyJSON's test backend, as Getting started does. Replace its URLs with your backend's.

Installation

To install the packages, run the following command:

npm install @monarcode/session-kit @tanstack/react-start @tanstack/react-router zod

1. Create the server engine

The server engine keeps the session in a cookie sealed with your secret, and refreshes the tokens with your backend. createServerAuth from @monarcode/session-kit/server makes it, and startAuth gives you the session of the request Start is handling. Create both in a server-only module, so Start refuses to bundle it for the browser:

src/auth/server.ts
import "@tanstack/react-start/server-only";
import {  } from "@monarcode/session-kit/server";
import {  } from "@monarcode/session-kit/tanstack-start/server";
import {  } from "zod";

export const  = "https://dummyjson.com";

const  = .({ : .(), : .() });
const  = .({ : .(), : .() });

export const  = ({
  : "app",
  : ,
  : ..SESSION_SECRET!,
  : async ({ ,  }) => {
    const  = await (`${}/auth/refresh`, {
      : "POST",
      ,
      : { "Content-Type": "application/json" },
      : .({  }),
    });
    // DummyJSON rejected the refresh token: sign out.
    if (. === 401 || . === 403) return null;
    if (!.) throw new (`Refresh failed (${.})`);
    return .(await .());
  },
});

/** The session of the request Start is handling, found on each call. */
export const  = ();

/** Signs in with your backend, from the server. */
export async function (: string, : string) {
  const  = await (`${}/auth/login`, {
    : "POST",
    : { "Content-Type": "application/json" },
    : .({ ,  }),
  });
  const : unknown = await .().(() => null);
  if (!.) {
    // The backend says why, such as wrong credentials, in `message`.
    const  = .({ : .() }).();
    throw new (
      .
        ? ..
        : `Sign-in failed (${.})`,
    );
  }
  return { ....(), : .() };
}

session finds the request each time it's called, so one object, made at module level, serves every request. Server sessions covers the engine's other options, the cookie, and signing out.

2. Add the session route and server functions

The browser's client signs out and gets the access token through a session route: a route in your app that the browser's client calls. sessionRoute from @monarcode/session-kit/tanstack-start/server makes its GET and POST handlers. Start leaves a route's server.handlers out of the browser bundle, and serverAuth with them:

src/routes/api/session.ts
import {  } from "@monarcode/session-kit/tanstack-start/server";
import {  } from "@tanstack/react-router";

import {  } from "../../auth/server";

export const  = ("/api/session")({
  : { : () },
});

The session route answers your own site's pages only, so another site can't sign the user out: see The session route.

Two server functions do the rest. One signs in with your form's input. The other reads the session, because loadSession reads it while Start renders on the server, where the client can't call a route on its own site:

src/auth/functions.ts
import {  } from "@tanstack/react-start";
import {  } from "zod";

import { ,  } from "./server";

export const  = ().(() =>
  .(),
);

export const  = ({ : "POST" })
  .(.({ : .(), : .() }))
  .(async ({  }) => {
    const  = await (., .);
    return .();
  });

getSession and signIn resolve { sessionId, user }, never tokens, so their results are safe to send to the browser. Start's compiler replaces each handler with a request in the browser bundle, and leaves session out of it.

3. Refresh before rendering

The server refreshes tokens that are about to expire before any route or server function reads them, while the response can still set the cookie. After Start starts streaming a page, a cookie set later is lost, and so are the new tokens. refreshSession from @monarcode/session-kit/tanstack-start/server does the refresh, in Start's own request middleware:

src/start.ts
import {  } from "@monarcode/session-kit/tanstack-start/server";
import {
  ,
  ,
  ,
} from "@tanstack/react-start";

import {  } from "./auth/server";

const  = ({ : "request" }).(
  (),
);

export const  = (() => ({
  : [
    ({
      : ({  }) =>  === "serverFn",
    }),
    ,
  ],
}));

Start bundles src/start.ts for the browser too, but strips what's inside .server(), so serverAuth stays on the server.

refreshSession refreshes access tokens that expire within 60 seconds. For tokens that live a minute or less, pass a smaller within, such as refreshSession(serverAuth, { within: 15 }). Refresh before rendering says what happens when a refresh fails.

createCsrfMiddleware protects your server functions, because an app that defines createStart has no CSRF check until it adds one. Here's what it covers:

  • Its filter limits the check to server-function calls. Without the filter, it also refuses page loads from links on other sites and from the address bar.
  • Filtered this way, it doesn't check server routes. sessionRoute refuses other sites itself. A server route of your own that changes the session must check too: see Check your own routes.

4. Create the browser client

The client that routes and components use comes from createMirrorAuth. It mirrors the session the server read, and calls your server functions and the session route. Create it in a function, not at module level:

src/auth/client.ts
import {  } from "@monarcode/session-kit";

import { ,  } from "./functions";

export function () {
  return ({
    : "app",
    : null, // filled by loadSession, then by hydration
    : "/api/session",
    : () => (),
    : (: { : string; : string }) =>
      ({  }),
  });
}

export type  = <typeof >;

Let TypeScript infer the client's types from its options. With createMirrorAuth<User>(…), signIn would be left out.

The Router creates the client in getRouter, which Start calls once per request on the server and once in the browser. connectSession sends the session the server read to the browser with the page, and runs the guards again when the session changes there:

src/router.tsx
import {  } from "@monarcode/session-kit/tanstack-start";
import {  } from "@tanstack/react-router";

import {  } from "./auth/client";
import {  } from "./routeTree.gen";

export function () {
  const  = ();
  const  = ({ , : {  } });
  ();
  return ;
}

declare module "@tanstack/react-router" {
  interface Register {
    : <typeof >;
  }
}

A dehydrate and a hydrate of your own, such as for a query cache, go to createRouter as usual. connectSession keeps them.

5. Load the session, then guard routes

The root route's beforeLoad reads the request's session into the client with loadSession, before any guard runs. In the browser, the session that came with the page is already there, so it doesn't call the server. The root route also renders the document, with <Scripts /> so the page hydrates, and an error component for when the session can't be read:

src/routes/__root.tsx
import type {  } from "react";

import {  } from "@monarcode/session-kit/tanstack-start";
import {
  ,
  ,
  ,
  ,
  ,
  type ,
} from "@tanstack/react-router";

import type {  } from "../auth/client";

export const  = <{ :  }>()({
  : ({  }) => (.),
  : ,
  : ,
  : ,
});

function ({  }: { :  }) {
  return (
    < ="en">
      <>
        < />
      </>
      <>
        {}
        < />
      </>
    </>
  );
}

function ({  }: ) {
  const  = ();
  return (
    < ="alert">
      <>{ instanceof  ? . : "Something went wrong"}</>
      {/* Runs loadSession again. */}
      < ={() => void .()}>Retry</>
    </>
  );
}

When the server can't read the session, such as after a failed refresh, loadSession rejects and SessionError shows. Its button calls router.invalidate(), which runs loadSession again.

Guards are the ones from @monarcode/session-kit/tanstack-router. On the server, a guard's redirect is a real HTTP redirect:

src/routes/_authenticated.tsx
import {
  ,
  ,
} from "@monarcode/session-kit/tanstack-router";
import {  } from "@tanstack/react-router";

export const  = ("/_authenticated")({
  : ({ ,  }) =>
    (., {  }),
  : () => < ={<>Loading…</>} />,
});

A signed-out user who opens a page under _authenticated, such as /orders, lands on /login?redirectTo=%2Forders. Guard private routes explains SessionOutlet. This route needs no error component of its own: loadSession reports a failed read first, in the root route.

Guards decide what a page shows. A server function that returns private data must check the session itself, with session.getSession() or session.credentials.get(), as getOrdersFn does in Call your API.

6. Sign in

The client's signIn sends what it's given to your signInFn, then takes the session it returns, runs the guards again and tells other tabs. A small helper turns a failure into the message to show:

src/sign-in.ts
import type {  } from "./auth/client";

/** Signs in, and resolves the message to show when it fails. */
export async function (
  : ,
  : string,
  : string,
): <string | null> {
  try {
    await .({ ,  });
    return null;
  } catch () {
    // What signInFn threw, such as your backend's message for a wrong
    // password.
    return  instanceof  ? . : "Could not sign in";
  }
}

The sign-in route has the redirectIfSignedIn guard, so a signed-in user goes on to redirectTo. Its form gets the client with useAuthClient, from Router context:

src/routes/login.tsx
import { , type  } from "react";

import {  } from "@monarcode/session-kit";
import {
  ,
  ,
} from "@monarcode/session-kit/tanstack-router";
import {  } from "@tanstack/react-router";

import {  } from "../sign-in";

export const  = ("/login")({
  : (: <string, unknown>) => ({
    : (.redirectTo),
  }),
  : ({ ,  }) =>
    (., { : . }),
  : ,
});

function () {
  const  = ();
  const [, ] = <string | null>(null);

  async function (: <>) {
    .();
    const  = new (.);
    const  = (.("username"));
    (await (, , (.("password"))));
  }

  return (
    < ={() => void ()}>
      <>
        Username
        < ="username" ="username" />
      </>
      <>
        Password
        <
          ="password"
          ="password"
          ="current-password"
        />
      </>
      { && < ="alert">{}</>}
      <>Sign in</>
    </>
  );
}

The form doesn't navigate after a sign-in. connectSession runs the guards again, and redirectIfSignedIn sends the user on. To try it, sign in as emilys with the password emilyspass. A wrong password shows DummyJSON's own message, which login threw.

In this guide, the server signs in with your backend, so the user in the cookie comes from the backend. If the browser has to sign in with the backend itself, for example through a provider's SDK, have signInFn take the tokens instead, as Hybrid setup shows.

7. Sign out

The client's signOut() signs out on the server through the session route, which clears the cookie and calls your revoke option, if createServerAuth has one. It then signs out this tab and tells the others. The guards run again, so requireSession sends the user to the sign-in page. Put a button like this one on any page under _authenticated:

src/sign-out.tsx
import {  } from "@monarcode/session-kit/tanstack-router";

export function () {
  const  = ();
  // A failed sign-out keeps the session, and shows in `state.error`.
  return (
    < ={() => void .().(() => {})}>
      Sign out
    </>
  );
}

Without revoke, a copy of the cookie made before sign-out still works: see Sign-out.

Call your API

Your server functions call your API with createAuthFetch from @monarcode/session-kit/http. Given session, it sends the access token of the request Start is handling, refreshed first if it has expired. Make it once, in a server-only module:

src/auth/auth-fetch.ts
import "@tanstack/react-start/server-only";
import {  } from "@monarcode/session-kit/http";

import { ,  } from "./server";

export const  = (, { : `${}/` });

Then call it in a server function. This one checks the session first, so it can ask for the signed-in user's orders:

src/orders.ts
import {  } from "@tanstack/react-start";
import {  } from "zod";

import {  } from "./auth/auth-fetch";
import {  } from "./auth/server";

const  = .({ : .(.({ : .() })) });

export const  = ().(async () => {
  const  = await .();
  if (!) throw new ("Sign in to see your orders");
  const  = await (`auth/carts/user/${..}`);
  if (!.) throw new (`Orders failed (${.})`);
  return .(await .()).;
});

When the user is signed out, authFetch rejects with UNAUTHENTICATED. When your API answers 401, it gets a new access token and saves it in the cookie. It sends a GET or HEAD again with the new token, as After a 401 explains.

With an HTTP client of your own, such as ky or axios, see Other HTTP clients. A client without a fetch option reads the token with session.credentials.get().

To call your API from the browser too, turn on clientCredentials in createServerAuth: see The access token in the browser. The example app does this.

Things to know

  • One session per request. Each call to session reads the request Start is handling, and calls during one request share what it read and one refresh. Outside a request, such as in the browser, its methods reject with INVALID_OPTIONS, and isCurrent and state throw it.
  • Caching. refreshSession sends Cache-Control: private, no-store with each response that doesn't set its own, so shared caches keep no user's page: see Refresh before rendering for cacheControl.
  • Prerendering. A prerendered page renders at build time, without a cookie, so it shows the signed-out state. Don't prerender pages that read the session.
  • Other tabs. Signing in or out in one tab reaches the others, which ask the server for the session and run the guards again: see How tabs stay in step.
  • Deploying. Several server instances, the cookie's size, and plain http during development are covered in Server sessions.

Next steps

On this page