Skip to Content

TanStack Start Integration

Integrate Entro Auth with TanStack Start.

This integration guide is assuming you are using TanStack Start.

Before you start, make sure you have a Entro Auth instance configured. If you haven't done that yet, check out the installation.

Quick Start

You can create a new TanStack Start project with Entro Auth integrated using the following command. This CLI sets up a project with an auth instance configured with the plugin and mounted handlers.

npm create @tanstack/start

◇  What add-ons would you like for your project?
│  Entro Auth

Usage

Mount the handler

We need to mount the handler to a TanStack API endpoint/Server Route. Create a new file: /src/routes/api/auth/$.ts

src/routes/api/auth/$.ts
import { auth } from '@/lib/auth'
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/api/auth/$')({
    server: {
        handlers: {
            GET: async ({ request }:{ request: Request }) => {
                return await auth.handler(request)
            },
            POST: async ({ request }:{ request: Request }) => {
                return await auth.handler(request)
            },
        },
    },
})

Usage tips

  • We recommend using the client SDK or authClient to handle authentication, rather than server actions with auth.api.
  • When you call functions that need to set cookies (like signOut) on the server, you'll need to handle cookie setting for TanStack Start. Entro Auth provides a tanstackStartCookies plugin to automatically handle this for you.
src/lib/auth.ts
import { entroAuth } from "@entro314labs/entro-auth";
import { tanstackStartCookies } from "@entro314labs/entro-auth/tanstack-start";

export const auth = entroAuth({
    //...your config
    plugins: [tanstackStartCookies()] // make sure this is the last plugin in the array
})

Now, when you call functions that set cookies, they will be automatically set using TanStack Start's cookie handling system.

src/lib/auth.functions.ts
import { createServerFn } from "@tanstack/react-start";
import { getRequestHeaders } from "@tanstack/react-start/server";
import { auth } from "@/lib/auth"

export const signOut = createServerFn({ method: "POST" }).handler(async () => {
    await auth.api.signOut({
        headers: getRequestHeaders()
    })
})

Protecting Resources

To protect resources that require authentication, use beforeLoad with a server function. This ensures authentication is checked on every navigation, including client-side navigation via <Link> components.

First, create server-side helpers to check the session:

src/lib/auth.functions.ts
import { createServerFn } from "@tanstack/react-start";
import { getRequestHeaders } from "@tanstack/react-start/server";
import { auth } from "@/lib/auth";

export const getSession = createServerFn({ method: "GET" }).handler(async () => {
    const headers = getRequestHeaders();
    const session = await auth.api.getSession({ headers });

    return session;
});

export const ensureSession = createServerFn({ method: "GET" }).handler(async () => {
    const headers = getRequestHeaders();
    const session = await auth.api.getSession({ headers });

    if (!session) {
        throw new Error("Unauthorized");
    }

    return session;
});

Protecting Routes

Use beforeLoad in your route definitions:

src/routes/dashboard.tsx
import { createFileRoute, redirect } from '@tanstack/react-router'
import { getSession } from '@/lib/auth.functions'

export const Route = createFileRoute('/dashboard')({
  beforeLoad: async () => {
    const session = await getSession();

    if (!session) {
      throw redirect({ to: "/login" });
    }

    return { user: session.user };
  },
  component: Dashboard,
})

function Dashboard() {
  const { user } = Route.useRouteContext();
  
  return <div>Welcome, {user.name}!</div>
}

Protecting Multiple Routes (Layout)

For protecting multiple routes, use a pathless layout route:

src/routes/_protected.tsx
import { createFileRoute, redirect, Outlet } from '@tanstack/react-router'
import { getSession } from '@/lib/auth.functions'

export const Route = createFileRoute('/_protected')({
  beforeLoad: async ({ location }) => {
    const session = await getSession();

    if (!session) {
      throw redirect({
        to: "/login",
        search: { redirect: location.href },
      });
    }

    return { user: session.user };
  },
  component: () => <Outlet />,
})

Then nest protected routes under _protected:

dashboard.tsx
settings.tsx
_protected.tsx
login.tsx

Protecting Server Functions

Use ensureSession helper to protect server functions:

src/lib/posts.functions.ts
import { createServerFn } from "@tanstack/react-start";
import { ensureSession } from "./auth.functions";

export const createPost = createServerFn({ method: "POST" })
  .inputValidator((data: { title: string }) => data)
  .handler(async ({ data }) => {
    const session = await ensureSession();
    const post = await db.posts.create({
      title: data.title,
      authorId: session.user.id,
    });
    
    return post;
  });

The integration package

@entro314labs/entro-auth-tanstack-start adds two things on top of the above: the handlers of the auth route for a server that builds its auth instance per request, and a session token for calling another API, both while a page is rendered on the server and in the browser.

npm install @entro314labs/entro-auth-tanstack-start

Both take a withAuth function, which runs work with an auth instance. With one instance for the whole server it is (run) => run(auth). On Cloudflare Workers it is what perRequest returns.

The auth route

src/routes/api/auth/$.ts
import { authHandlers } from "@entro314labs/entro-auth-tanstack-start/server";
import { createFileRoute } from "@tanstack/react-router";
import { withAuth } from "@/lib/auth";

export const Route = createFileRoute("/api/auth/$")({
  server: { handlers: authHandlers(withAuth) },
});

A session token for another API

When your data comes from a service of its own, that service does not see the session cookie. The JWT plugin signs a short-lived token it can verify. A TanStack Start app needs that token in two places, the browser and the server that renders the first page, and signing one on the server for every page view costs a database round trip each time.

tokenStore asks /token once in the browser and keeps the answer, in memory and in a cookie, until shortly before it runs out. sessionToken reads it from that cookie while a page is rendered, and signs one only when the request brings none. A visitor without a session cookie costs nothing on either side.

src/lib/session-token.ts
import { tokenStore } from "@entro314labs/entro-auth-tanstack-start/client";
import { sessionToken } from "@entro314labs/entro-auth-tanstack-start/server";
import { createIsomorphicFn } from "@tanstack/react-start";
import { withAuth } from "@/lib/auth";
import { authClient } from "@/lib/auth-client";

export const tokens = tokenStore(authClient);
const serverToken = sessionToken(withAuth);

/** The token to send as `Authorization: Bearer`, or null when nobody is signed in. */
export const getSessionToken = createIsomorphicFn()
  .server(() => serverToken())
  .client(() => tokens.get());

The server needs the jwt plugin and the client jwtClient. Keep createIsomorphicFn in your own file: the Start compiler splits server and browser code in your source, not inside a package.

Call tokens.forget() when the person signs in or out, so the next request asks again:

const session = authClient.useSession();
const userId = session.data?.user.id ?? null;

useEffect(() => {
  tokens.forget();
  void queryClient.invalidateQueries();
}, [userId]);

On the first page after a reload nothing changed, so skip that run when tokens.keptSubject() is null or equal to the user who turns out to be signed in.

The token in the cookie is not verified by this package, on either side. The API that receives it verifies it. JavaScript on your page can read the cookie; it could also ask /token for the same token.

A token outlives the session and the user it was signed for by its lifetime, 15 minutes by default. See what a token does not tell you.

On this page