Skip to content

feat(tanstack-start): Add Tanstack Start integration package - #255

Draft
halvaradop wants to merge 5 commits into
masterfrom
feat/add-tanstack-start-pkg
Draft

feat(tanstack-start): Add Tanstack Start integration package#255
halvaradop wants to merge 5 commits into
masterfrom
feat/add-tanstack-start-pkg

Conversation

@halvaradop

@halvaradop halvaradop commented Aug 7, 2026

Copy link
Copy Markdown
Member

Description

This pull request introduces the @aura-stack/tanstack-start integration package, providing seamless Aura Auth integration for TanStack Start applications.

The package is built on top of @aura-stack/auth and provides the server-side and client-side APIs required to integrate authentication into TanStack Start applications. It exposes server functions, client-side context and hooks, and native authentication utilities while following the conventions and capabilities of the TanStack Start framework.

For the client-side implementation, the package internally uses @aura-stack/react to provide the authentication context and React hooks, while adding a TanStack Start-specific layer for server functions and framework integration.

Key Changes

  • Added the new TanStack Start integration package.
  • Added TanStack Start server functions for authentication operations.
  • Added client-side authentication context and hooks.
  • Reused @aura-stack/react for the client-side authentication layer.
  • Added TanStack Start-specific APIs on top of the core @aura-stack/auth functionality.
  • Exposed the native utilities provided by the core authentication package.

Architecture

The integration is structured in layers:

@aura-stack/auth
        ↓
@aura-stack/react
        ↓
@aura-stack/tanstack-start
        ↓
TanStack Start application

@aura-stack/auth provides the core authentication functionality, @aura-stack/react handles the React client-side layer, and @aura-stack/tanstack-start adds the framework-specific server functions and TanStack Start integration.

TODO

This PR is not ready to be merged yet. The following tasks must be completed before the integration is considered ready:

  • Add native redirection support from @tanstack/react-router.
  • Update the apps/tanstack-start demo application with a complete and useful example.
  • Add and verify redirection behavior through tests.

Note

This package is currently under active development. The remaining tasks are required to complete the TanStack Start integration and ensure that authentication, navigation, and redirection behave consistently with the other Aura Stack framework integrations.

@vercel

vercel Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
auth Ready Ready Preview Aug 9, 2026 5:02pm

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review Change Stack

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 2c3f51a2-2b07-487e-bbcd-0210da3a3858

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a TanStack Start authentication package with typed factories, client hooks, server-function wrappers, package exports, tests, build configuration, documentation, and application wiring. It also updates identity exports and reformats the generated route tree.

Changes

TanStack Start authentication

Layer / File(s) Summary
Package surface and build configuration
packages/tanstack-start/deno.json, packages/tanstack-start/package.json, packages/tanstack-start/tsconfig.json, packages/tanstack-start/tsdown.config.ts, packages/tanstack-start/vitest.config.ts, packages/tanstack-start/CHANGELOG.md, packages/tanstack-start/README.md
Defines package metadata, exports, scripts, dependencies, source mappings, build entries, compiler settings, publishing rules, tests, and documentation.
Typed authentication factory and client surface
packages/tanstack-start/src/@types/*, packages/tanstack-start/src/createAuth.ts, packages/tanstack-start/src/client.tsx, packages/tanstack-start/src/context.tsx, packages/tanstack-start/src/index.ts
Adds typed authentication contracts, the createAuth factory, client exports, the AuthProvider wrapper, and public package exports.
Server-function authentication API
packages/tanstack-start/src/lib/api.ts
Adds typed server functions for session, authentication, OAuth token, user-info, token revocation, provider, and connectivity operations.
Application migration to TanStack Start
apps/tanstack-start/package.json, apps/tanstack-start/src/*
Switches the example application to the TanStack Start package, updates client hooks and server API calls, adds the DELETE handler, and changes authentication payloads.
Server API and type validation
packages/tanstack-start/test/*
Adds request and authentication mocks, API handler tests, response sanitization checks, forwarding checks, and compile-time generic inference tests.

Integration exports and generated output

Layer / File(s) Summary
Identity package exports
packages/integration/deno.json, packages/integration/package.json, packages/integration/tsdown.config.ts
Updates the identity entry point, adds schema integration exports, and exposes identity submodules through wildcard mappings.
Generated route tree formatting
apps/tanstack-start/src/routeTree.gen.ts
Reformats the generated route tree while retaining its routes, metadata, type mappings, child wiring, and React Start registration.

Estimated code review effort: 3 (Moderate) | ~30 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant TanStackServerFunction
  participant AuthAPI
  Client->>TanStackServerFunction: Submit typed authentication input
  TanStackServerFunction->>AuthAPI: Forward input, headers, and request context
  AuthAPI-->>TanStackServerFunction: Return authentication result
  TanStackServerFunction-->>Client: Return data without transport fields
Loading

Possibly related PRs

  • aura-stack-ts/auth#117: Provides the createAuth.api and authentication hook patterns used by this integration.
  • aura-stack-ts/auth#141: Establishes the analogous integration-package structure extended for TanStack Start.
  • aura-stack-ts/auth#253: Adds a parallel framework-specific Aura Stack integration with matching factory, export, and request-handling patterns.

Suggested labels: enhancement, feature

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the addition of the TanStack Start integration package, which is the main change.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/add-tanstack-start-pkg

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (1)
packages/tanstack-start/src/lib/api.ts (1)

139-148: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the unreferenced test server function.

This handler is not returned by api and returns hard-coded test data. Remove it so the package does not compile an unrelated server function.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/tanstack-start/src/lib/api.ts` around lines 139 - 148, Remove the
unreferenced createServerFn GET handler that returns the hard-coded “jose” test
data, leaving the exported api implementation and its referenced server
functions unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/tanstack-start/package.json`:
- Around line 3-4: Remove the "private": true field from
packages/tanstack-start/package.json so the package remains publishable; retain
the existing public publishing configuration.
- Around line 74-83: Update the package exports for "./identity" and
"./identity/*" to match the emitted entries from src/identity.ts and
src/identity/*.ts, routing them to dist/identity outputs; leave the
_core/identity entry under its core namespace unless src/_core/identity.ts is
explicitly intended as the package-root entry.

In `@packages/tanstack-start/README.md`:
- Around line 3-20: Update packages/tanstack-start/README.md lines 3-20 to
replace all `@aura-stack/integration` branding, metadata, documentation links, and
installation references with `@aura-stack/tanstack-start`. In
packages/tanstack-start/CHANGELOG.md line 13, remove the /client claim unless a
matching ./client export and build entry are added to the package manifest and
build configuration.

In `@packages/tanstack-start/src/`@types/index.ts:
- Around line 57-59: Update TanstackStartUpdateSessionReturn to omit only
"headers" and "toResponse", keeping "session" in the public result type so it
matches the value returned by the update-session handler.

In `@packages/tanstack-start/src/index.ts`:
- Line 1: Update the package entry point alongside createAuth to re-export the
intended public types from src/@types/index.ts, ensuring consumers can import
those named types from the root package without requiring a separate subpath.

In `@packages/tanstack-start/src/lib/api.ts`:
- Around line 52-53: Update the handler around the output destructuring to
import and call setResponseHeaders with output.headers before returning data,
preserving authentication cookies and other metadata. Handle output.toResponse
in the core API path by returning its full Response or redirect when required,
while retaining the serializable result path for normal responses.

---

Nitpick comments:
In `@packages/tanstack-start/src/lib/api.ts`:
- Around line 139-148: Remove the unreferenced createServerFn GET handler that
returns the hard-coded “jose” test data, leaving the exported api implementation
and its referenced server functions unchanged.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 56bb2df8-9a64-485c-a715-b38dac099790

📥 Commits

Reviewing files that changed from the base of the PR and between 1c76888 and 86a30eb.

⛔ Files ignored due to path filters (3)
  • bun.lock is excluded by !**/*.lock
  • deno.lock is excluded by !**/*.lock
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (13)
  • apps/tanstack-start/src/routeTree.gen.ts
  • packages/integration/deno.json
  • packages/integration/package.json
  • packages/tanstack-start/CHANGELOG.md
  • packages/tanstack-start/README.md
  • packages/tanstack-start/deno.json
  • packages/tanstack-start/package.json
  • packages/tanstack-start/src/@types/index.ts
  • packages/tanstack-start/src/createAuth.ts
  • packages/tanstack-start/src/index.ts
  • packages/tanstack-start/src/lib/api.ts
  • packages/tanstack-start/tsconfig.json
  • packages/tanstack-start/tsdown.config.ts

Comment thread packages/tanstack-start/package.json Outdated
Comment thread packages/tanstack-start/package.json
Comment thread packages/tanstack-start/README.md Outdated
Comment thread packages/tanstack-start/src/@types/index.ts Outdated
Comment thread packages/tanstack-start/src/index.ts
Comment on lines +52 to +53
const { headers: _h, toResponse: _t, ...spread } = output
return spread

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate file =="
git ls-files | grep 'packages/tanstack-start/src/lib/api.ts' || true

echo "== file excerpt =="
if [ -f packages/tanstack-start/src/lib/api.ts ]; then
  nl -ba packages/tanstack-start/src/lib/api.ts | sed -n '1,240p'
fi

echo "== search setResponseHeaders and relevant wrappers =="
rg -n "setResponseHeaders|toResponse|Set-Cookie|createServerFn|output\.headers|headers:" packages/tanstack-start/src/lib/api.ts packages/tanstack-start || true

echo "== package version/docs hints =="
fd -a 'README.md|package.json|index.ts|server.ts|lib/api.ts' packages/tanstack-start 2>/dev/null | sed -n '1,120p' || true

Repository: aura-stack-ts/auth

Length of output: 272


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== file excerpt =="
if [ -f packages/tanstack-start/src/lib/api.ts ]; then
  awk '{printf "%6d: %s\n", NR, $0}' packages/tanstack-start/src/lib/api.ts | sed -n '1,240p'
fi

echo "== search relevant symbols =="
rg -n "setResponseHeaders|toResponse|Set-Cookie|createServerFn|output\.headers|headers:" packages/tanstack-start/src/lib/api.ts packages/tanstack-start || true

echo "== package version clues =="
for f in packages/tanstack-start/package.json packages/tanstack-start/README.md; do
  if [ -f "$f" ]; then
    echo "--- $f ---"
    sed -n '1,220p' "$f"
  fi
done

echo "== tanstack start package docs/source hints =="
rg -n "setResponseHeaders|responseHeaders|headers:" node_modules packages 2>/dev/null | head -200 || true

Repository: aura-stack-ts/auth

Length of output: 41492


🌐 Web query:

TanStack Start createServerFn response headers setResponseHeaders documentation

💡 Result:

In TanStack Start, you can manage response headers within a server function by importing the server utilities from @tanstack/react-start/server (or the equivalent for your framework) [1][2]. The setResponseHeaders utility allows you to set multiple response headers at once using a Headers object or a plain object [2][3]. ### Example Usage tsx import { createServerFn } from '`@tanstack/react-start`' import { setResponseHeaders, setResponseStatus } from '`@tanstack/react-start/server`' export const getMyData = createServerFn({ method: 'GET' }).handler(async () => { // Using a Headers object setResponseHeaders( new Headers({ 'Cache-Control': 'private, max-age=60', 'Vary': 'Cookie, Authorization', }), ) // Or using a plain object setResponseHeaders({ 'X-Custom-Header': 'my-value' }) setResponseStatus(200) return { data: 'example' } }) ### Available Server Utilities Beyond setResponseHeaders, the following server context utilities are available for managing response state: * setResponseHeader(name, value): Sets a single response header [1][2]. * setResponseHeaders(headers): Sets multiple response headers [2][3]. * setResponseStatus(code): Sets the HTTP status code for the response [1][2]. * removeResponseHeader(name): Removes a specific response header [2]. * clearResponseHeaders: Clears all response headers [2]. * getResponseHeader(name): Retrieves a specific response header [2]. * getResponseHeaders: Retrieves all currently set response headers [2]. * getResponseStatus: Retrieves the current response status code [2]. These utilities are available within the server function handler via AsyncLocalStorage, allowing them to be called anywhere within the request call stack [2].

Citations:


🌐 Web query:

TanStack Start server functions response headers setResponseHeaders

💡 Result:

In TanStack Start, you can manage response headers within server functions by importing helper utilities from @tanstack/<framework>-start/server (e.g., @tanstack/react-start/server) [1][2]. These utilities must be used exclusively on the server side and will throw an error if accessed in a client-side context [2]. The following utilities are available for managing response headers: setResponseHeaders(headers): Sets multiple response headers at once using a Headers object or a plain object [1][2][3]. setResponseHeader(name, value): Sets a single response header [1][2][3]. getResponseHeaders: Returns the current response headers [2][3]. getResponseHeader(name): Retrieves a specific response header [2][3]. removeResponseHeader(name): Removes a specific response header [3]. clearResponseHeaders(headerNames?): Clears all response headers, or specific ones if provided as an array [3]. Example usage: import { createServerFn } from '@tanstack/react-start' import { setResponseHeader, setResponseHeaders } from '@tanstack/react-start/server' export const myServerFn = createServerFn({ method: 'GET' }).handler(async => { // Set multiple headers setResponseHeaders( new Headers({ 'Cache-Control': 'private, max-age=60', 'Vary': 'Cookie, Authorization', }),) // Set a single header setResponseHeader('x-custom-header', 'my-value') return { success: true } }) Note that these utilities rely on the server request context (provided via AsyncLocalStorage) and are designed to be used inside your server function handler [2].

Citations:


🌐 Web query:

aura-stack @Aura-Stack integration TanstackStartSignInReturn headers toResponse

💡 Result:

In Aura Stack, the Auth API responses (including those from sign-in operations) are designed to provide interoperability with server-side frameworks like TanStack Start through a structured response type [1]. When you perform an authentication operation—such as a sign-in—the API returns a structured object that includes: - headers: An instance of the Headers interface containing necessary cookies or security headers [1]. - toResponse: An adapter function that generates a standard HTTP Response object [1]. In the context of TanStack Start integration, these properties allow you to bridge the authentication state between the Aura Auth API and the TanStack Start request/response lifecycle. If you need to propagate these headers back to the browser (e.g., setting session cookies), you should extract the headers from the API response and apply them to the TanStack Start response context [1][2]. Example pattern for using headers in TanStack Start: 1. Call the Aura Auth API action within a TanStack createServerFn [3]. 2. Retrieve the headers returned by the API [1]. 3. Apply the headers to the TanStack Start response using server utilities (such as setting cookies or response headers) or by returning them in a redirect or response object [3][4]. The returned type follows this structure [1]: { success: boolean, headers: Headers, toResponse: => Response, error?: { code: string, message: string } } By utilizing the toResponse method or manually extracting and setting the headers, you ensure that authentication state (like session cookies) is correctly persisted and communicated in your TanStack Start application [1][2].

Citations:


Forward authentication response metadata before returning data.

These handlers discard output.headers and output.toResponse, so TanStack Start handlers do not copy cookies back, including Set-Cookie from sign-in, sign-up, sign-out, refresh, token, session, and provider operations. Import setResponseHeaders from @tanstack/react-start/server and call it with output.headers before returning the serializable result. Also handle output.toResponse where the core API path requires returning a full Response or redirect instead of JSON data.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/tanstack-start/src/lib/api.ts` around lines 52 - 53, Update the
handler around the output destructuring to import and call setResponseHeaders
with output.headers before returning data, preserving authentication cookies and
other metadata. Handle output.toResponse in the core API path by returning its
full Response or redirect when required, while retaining the serializable result
path for normal responses.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/tanstack-start/src/lib/auth.ts`:
- Line 12: Update the provider configuration near oauth to match the demo
controls: either add bitbucket to the enabled provider list so
signIn("bitbucket") succeeds, or remove the Bitbucket controls and related
user-facing text from the client and server routes. Keep the configuration and
available sign-in options consistent.

In `@packages/tanstack-start/src/`@types/index.ts:
- Around line 158-165: Update the RefreshUserInfo type to use RequiredFetcher
instead of OptionalFetcher, and set its input type to
TanstackStartRefreshUserInfoOptions so auth.api.refreshUserInfo requires the
validated provider options, including oauth.

In `@packages/tanstack-start/test/types.test-d.ts`:
- Line 20: Remove the redundant FromShapeToObject transformation from the
expected types in the auth.api.getSession assertions at the referenced test
lines. Reuse the identity object type already produced by the earlier
schema-shape resolution, while preserving the existing nullability and session
return-type contract.

In `@packages/tanstack-start/vitest.config.ts`:
- Around line 12-16: Update vitest.config.ts to avoid __dirname in the ESM
module: derive the configuration directory from import.meta.url using the
node:url and node:path utilities, then use that directory when resolving the "@"
and "`@test`" aliases. Preserve the existing alias targets.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d30bd97f-9680-4172-8f94-ef258be731cc

📥 Commits

Reviewing files that changed from the base of the PR and between 86a30eb and a224986.

⛔ Files ignored due to path filters (2)
  • bun.lock is excluded by !**/*.lock
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (38)
  • apps/tanstack-start/package.json
  • apps/tanstack-start/src/components/header.tsx
  • apps/tanstack-start/src/contexts/auth.tsx
  • apps/tanstack-start/src/lib/auth-client.ts
  • apps/tanstack-start/src/lib/auth-server.ts
  • apps/tanstack-start/src/lib/auth.ts
  • apps/tanstack-start/src/routes/api/auth.$.ts
  • apps/tanstack-start/src/routes/client.tsx
  • apps/tanstack-start/src/routes/server.tsx
  • packages/integration/package.json
  • packages/integration/tsdown.config.ts
  • packages/tanstack-start/README.md
  • packages/tanstack-start/package.json
  • packages/tanstack-start/src/@types/api.ts
  • packages/tanstack-start/src/@types/core.ts
  • packages/tanstack-start/src/@types/index.ts
  • packages/tanstack-start/src/client.tsx
  • packages/tanstack-start/src/context.tsx
  • packages/tanstack-start/src/createAuth.ts
  • packages/tanstack-start/src/index.ts
  • packages/tanstack-start/src/lib/api.ts
  • packages/tanstack-start/test/api/disconnectProvider.test.ts
  • packages/tanstack-start/test/api/getAccessToken.test.ts
  • packages/tanstack-start/test/api/getProviderTokens.test.ts
  • packages/tanstack-start/test/api/getSession.test.ts
  • packages/tanstack-start/test/api/isProviderConnected.test.ts
  • packages/tanstack-start/test/api/refreshUserInfo.test.ts
  • packages/tanstack-start/test/api/revokeToken.test.ts
  • packages/tanstack-start/test/api/signIn.test.ts
  • packages/tanstack-start/test/api/signInCredentials.test.ts
  • packages/tanstack-start/test/api/signOut.test.ts
  • packages/tanstack-start/test/api/signUp.test.ts
  • packages/tanstack-start/test/api/test-utils.ts
  • packages/tanstack-start/test/api/updateSession.test.ts
  • packages/tanstack-start/test/types.test-d.ts
  • packages/tanstack-start/tsconfig.json
  • packages/tanstack-start/tsdown.config.ts
  • packages/tanstack-start/vitest.config.ts
💤 Files with no reviewable changes (1)
  • apps/tanstack-start/src/lib/auth-server.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • packages/tanstack-start/src/createAuth.ts
  • packages/tanstack-start/tsdown.config.ts
  • packages/tanstack-start/tsconfig.json
  • packages/tanstack-start/src/index.ts
  • packages/tanstack-start/package.json

api,
core: { jose },
} = createAuth({
oauth: ["github", "google", "gitlab"],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Keep the enabled provider list consistent with the demo controls.

This configuration excludes bitbucket. apps/tanstack-start/src/routes/client.tsx and apps/tanstack-start/src/routes/server.tsx still submit signIn("bitbucket"). That sign-in path will fail. Enable Bitbucket or remove its controls and related user-facing text.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/tanstack-start/src/lib/auth.ts` at line 12, Update the provider
configuration near oauth to match the demo controls: either add bitbucket to the
enabled provider list so signIn("bitbucket") succeeds, or remove the Bitbucket
controls and related user-facing text from the client and server routes. Keep
the configuration and available sign-in options consistent.

Comment on lines +158 to +165
type RefreshUserInfo<Identity extends Identities> = OptionalFetcher<
undefined,
any,
Promise<{
success: boolean
session: Session<FromShapeToObject<Identity>> | null
}>
>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 10 'refreshUserInfo|TanstackStartRefreshUserInfoOptions' \
  packages/tanstack-start/src/lib/api.ts \
  packages/tanstack-start/src/@types \
  packages/tanstack-start/test

Repository: aura-stack-ts/auth

Length of output: 22388


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the surrounding file sections and related type definitions.
sed -n '1,240p' packages/tanstack-start/src/@types/index.ts
printf '\n--- packages/tanstack-start/src/@types/api.ts ---\n'
sed -n '50,90p' packages/tanstack-start/src/@types/api.ts
printf '\n--- packages/tanstack-start/src/lib/api.ts imports/refreshUserInfo section ---\n'
sed -n '1,40p' packages/tanstack-start/src/lib/api.ts
sed -n '140,162p' packages/tanstack-start/src/lib/api.ts

# Find definitions for RequiredFetcher/OptionalFetcher and refreshUserInfo API options.
printf '\n--- fetcher definitions ---\n'
rg -n 'type RequiredFetcher|interface RequiredFetcher|export .*RequiredFetcher|typeof RequiredFetcher|type OptionalFetcher|interface OptionalFetcher|export .*OptionalFetcher' .
printf '\n--- RefreshUserInfoAPIOptions / OAuth provider definitions ---\n'
rg -n 'RefreshUserInfoAPIOptions|RefreshUserInfoAPIReturn|interface .*OAuth|type .*Build|BuiltInOAuthProvider|type.*OAuthProvider' packages

Repository: aura-stack-ts/auth

Length of output: 31363


Require the refresh-user-info input.

TanstackStartRefreshUserInfoOptions requires oauth, and the server function validates data as that type, but RefreshUserInfo exposes any input via OptionalFetcher. This lets auth.api.refreshUserInfo(...) accept missing or untyped provider options. Use RequiredFetcher and keep the input type aligned with .validator((data: TanstackStartRefreshUserInfoOptions) => data).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/tanstack-start/src/`@types/index.ts around lines 158 - 165, Update
the RefreshUserInfo type to use RequiredFetcher instead of OptionalFetcher, and
set its input type to TanstackStartRefreshUserInfoOptions so
auth.api.refreshUserInfo requires the validated provider options, including
oauth.

})
type Identity = FromShapeToObject<IdentityShape & { role: zod.ZodString; nickname: zod.ZodOptional<zod.ZodString> }>

expectTypeOf<Awaited<ReturnType<typeof auth.api.getSession>>>().toEqualTypeOf<FromShapeToObject<Identity> | null>()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Remove the second identity-shape transformation.

Line 18 already resolves the schema shape to the user object type. Lines 20 and 34 apply FromShapeToObject again. This can make the type test fail or validate the wrong contract.

Proposed fix
-        expectTypeOf<Awaited<ReturnType<typeof auth.api.getSession>>>().toEqualTypeOf<FromShapeToObject<Identity> | null>()
+        expectTypeOf<Awaited<ReturnType<typeof auth.api.getSession>>>().toEqualTypeOf<Identity | null>()
...
-            session: Session<FromShapeToObject<Identity>> | null
+            session: Session<Identity> | null

Also applies to: 34-34

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/tanstack-start/test/types.test-d.ts` at line 20, Remove the
redundant FromShapeToObject transformation from the expected types in the
auth.api.getSession assertions at the referenced test lines. Reuse the identity
object type already produced by the earlier schema-shape resolution, while
preserving the existing nullability and session return-type contract.

Comment on lines +12 to +16
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
"@test": path.resolve(__dirname, "./test"),
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

jq -r '.type // "commonjs-default"' packages/tanstack-start/package.json
rg -n -C 3 '__dirname|import\.meta\.url|configLoader' packages/tanstack-start/vitest.config.ts packages/tanstack-start/package.json

Repository: aura-stack-ts/auth

Length of output: 682


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "package.json module type:"
jq -r '"\(.type // "commonjs-default") :: \(.imports // {} | keys | join(","))"' packages/tanstack-start/package.json

echo
echo ".ts config file imports/exports:"
sed -n '1,80p' packages/tanstack-start/vitest.config.ts

echo
echo "workspace/root package config hints:"
for f in package.json tsconfig.json tsconfig.base.json; do
  if [ -f "$f" ]; then
    echo "--- $f ---"
    jq -r 'if . then ("package modules: " + (.type // "commonjs-default") + " :: " + ((.imports // {}) | keys | join(","))) else "missing" end' "$f" 2>/dev/null || true
  fi
done

echo
echo "root vitest files:"
git ls-files | rg '(^|/)vitest\.config\.(ts|js|mjs|cts|mcts|mts)$|vitest\.config\.(ts|js|mjs|cts|mcts)\.ts$' | sort

Repository: aura-stack-ts/auth

Length of output: 1190


🌐 Web query:

Vitest config file TypeScript __dirname .vitest.config.ts ESM package.json type module

💡 Result:

In an ESM-based project where your package.json contains "type": "module", you cannot use the CommonJS dirname variable directly in your configuration files, as it is not defined in ESM scope [1][2]. To resolve this while using a TypeScript configuration file (e.g., vitest.config.ts or vitest.config.mts), you should manually derive dirname using the path and url modules [3][2]. Recommended Approach 1. Use the.mts extension: Rename your config file to vitest.config.mts [3]. This explicitly signals to Vitest and Node.js that the file should be treated as an ES Module [2]. 2. Derive dirname: Add the following boilerplate to your configuration file [3]: import { defineConfig } from 'vitest/config'; import { fileURLToPath } from 'url'; import path from 'path'; const dirname = path.dirname(fileURLToPath(import.meta.url)); export default defineConfig({ test: { // your test configuration }, }); Key Considerations - Configuration File Priority: Vitest automatically searches for configuration files in the project root [4]. Files named vitest.config.* (including.ts,.mts,.js,.mjs) take precedence over vite.config.* files [4][5]. - ESM vs. CJS: When "type": "module" is set in package.json, Node.js enforces ESM rules [2]. While Vitest sometimes provides shims for CJS globals (like dirname) in test files during runtime, relying on them in your ESM-based configuration file will cause ReferenceErrors [1][6]. Manually deriving the variable as shown above is the standard, reliable practice [3][2]. - TypeScript Support: Since you are using TypeScript, Vitest natively supports.ts and.mts configuration files [4]. Using.mts is preferred for explicit ESM handling [3].

Citations:


🌐 Web query:

site:vitest.dev config file vitest.config.ts module type dirname import.meta.url

💡 Result:

In a vitest.config.ts file, which is typically executed as an ES module, dirname and filename are not defined by default as they are in CommonJS. To resolve the directory path of the current configuration file in an ES module environment, you must use import.meta.url [1]. You can reconstruct dirname by using the node:url and node:path modules: import { fileURLToPath } from 'node:url'; import { dirname } from 'node:path'; import { defineConfig } from 'vitest/config'; const dirname = dirname(fileURLToPath(import.meta.url)); export default defineConfig({ // Your configuration here }); It is important to note that Vitest historically provided a "module runner" sandbox in its test execution environment that would inject variables like dirname and filename [1]. However, relying on this injection in your configuration file is not standard practice for modern ESM-based Node.js projects, and newer versions of Vitest are moving toward stricter native ESM behavior [1]. Using the standard Node.js approach shown above ensures your configuration remains compatible and predictable outside of the Vitest sandbox.

Citations:


🌐 Web query:

Vitest 4.3 vitest.config.ts ESM package type module __dirname defineConfig

💡 Result:

In Vitest 4.3 (or any version within the v4.x release line), using dirname within a vitest.config.ts file while your project is configured as "type": "module" follows standard Node.js ESM patterns [1][2]. Since Node.js ECMAScript modules (ESM) do not natively provide the dirname global variable [2], you must define it manually if you need to use it for path resolution in your configuration [1]. Recommended Approach To use dirname in an ESM vitest.config.ts, you should derive it using import.meta.url [2]: import { defineConfig } from 'vitest/config'; import { fileURLToPath } from 'node:url'; import { dirname, resolve } from 'node:path'; const dirname = dirname(fileURLToPath(import.meta.url)); export default defineConfig({ resolve: { alias: { '@': resolve(dirname, './src'), }, }, test: { // Vitest configuration }, }); Key Considerations 1. Module Resolution: When "type": "module" is set in your package.json, Node.js treats.ts files as ESM [3][2]. The manual definition shown above is the standard, type-safe way to access directory paths [1]. 2. Alternative File Extension: If you prefer not to manually define dirname, you can rename your configuration file to vitest.config.mts (the 'm' stands for module). Vitest and Vite treat.mts files as ESM automatically, though you may still need to use import.meta.url for path resolution if you choose to follow strict ESM standards [3]. 3. Vitest Compatibility: These practices remain consistent across Vitest 4.x versions [4][5]. The configuration structure utilizing defineConfig remains the primary method for defining Vitest settings [6][1]. Top results: 6, 7, 10, 11, 13

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "lockfile references for vitest/vite/config loader:"
if [ -f "pnpm-lock.yaml" ]; then
  jq 'if type=="object" and .lockfileVersion then "pnpm" else "not pnpm" end' pnpm-lock.yaml 2>/dev/null || true
  rg -n "(`@vitest/`|vitest@|vite@|configLoader|vitest/config)" pnpm-lock.yaml | head -80
elif [ -f "package-lock.json" ]; then
  jq -r '.packages["node_modules/vitest"].version // empty, .packages["node_modules/vite"].version // empty, .packages["node_modules/@vitest/config"].version // empty, .packages["node_modules/@vitest/vite"].version // empty' package-lock.json 2>/dev/null || true
elif [ -f "yarn.lock" ]; then
  rg -n "(vitest|`@vitest/`|vite|configLoader):" yarn.lock | head -80
fi

echo
echo "package dependencies:"
jq '.dependencies, .devDependencies' packages/tanstack-start/package.json | rg -n "(vitest|vite|`@vitejs`|`@vitest`|typescript)" || true

Repository: aura-stack-ts/auth

Length of output: 15224


🌐 Web query:

github vitest 4.1.4 vitest.config.ts __dirname type module loader

💡 Result:

Vitest 4.1.4 was released on April 9, 2026 [1][2][3]. Regarding the use of dirname in vitest.config.ts when using "type": "module" in package.json: 1. The Issue: In Node.js ES modules, dirname and filename are not available by default [4][5]. If your vitest.config.ts is treated as an ES module (which is the default when "type": "module" is set), attempting to use dirname directly will cause a ReferenceError [5]. 2. The Recommended Solution: You should define dirname manually using import.meta.url and the url module [6][5]. This ensures your configuration remains compatible with standard Node.js ESM behavior. Example implementation: import { fileURLToPath } from 'url'; import { dirname } from 'path'; import { defineConfig } from 'vitest/config'; const dirname = dirname(fileURLToPath(import.meta.url)); export default defineConfig({ // Your configuration here resolve: { alias: { '@': ${dirname}/src } } }); 3. Vitest Context: While Vitest (via vite-node) sometimes injects dirname shims into your test files during runtime to maintain compatibility with legacy codebases [4][7], it does not automatically polyfill it for your vitest.config.ts file itself [5]. For configuration files, you are responsible for providing a valid Node.js environment compatible with the module type defined in your package.json [5].

Citations:


Make the Vitest config ESM-safe.

packages/tanstack-start/package.json sets "type": "module", so vitest.config.ts runs as ESM and __dirname is undefined. Derive the config directory from import.meta.url, for example:

import { fileURLToPath, URL } from "node:url"
import { dirname, resolve } from "node:path"
const configDir = dirname(fileURLToPath(new URL("./", import.meta.url)))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/tanstack-start/vitest.config.ts` around lines 12 - 16, Update
vitest.config.ts to avoid __dirname in the ESM module: derive the configuration
directory from import.meta.url using the node:url and node:path utilities, then
use that directory when resolving the "@" and "`@test`" aliases. Preserve the
existing alias targets.

@halvaradop
halvaradop marked this pull request as draft August 8, 2026 16:24
@halvaradop

Copy link
Copy Markdown
Member Author

This pull request remains in draft status while investigating issues encountered in the TanStack Start integration.

After investigating the behavior, I have not yet identified the root cause of the issues. It is currently unclear whether they are caused by mismatched TanStack dependencies, the bundled @aura-stack/tanstack-start package, or an interaction between the integration and TanStack Start itself.

As part of the investigation, I updated the TanStack dependencies to their latest versions, but the issues persisted.

I also verified whether @aura-stack/tanstack-start was responsible for the behavior. The investigation showed that the server functions provided by the package are correctly registered and executed by TanStack Start. This was confirmed through logging inside the functions. However, despite being executed, the functions do not return any value to the caller.

For example, even when returning simple values such as strings or booleans for testing purposes, the caller consistently receives undefined:

export const testFunction = createServerFn().handler(() => {
  console.log("Server function executed")
  return "test"
})

The function is executed correctly, but the returned value is unexpectedly undefined.

Client-Side Investigation

I also investigated the client-side behavior independently of the TanStack Start server functions by using the native React primitives and the authClient instance provided by Aura Auth.

However, the same unexpected behavior occurs on the client side.

A useEffect callback was not being executed as expected, and requests made through the authClient were not being triggered either. For example, the authentication client does not make the expected request to endpoints such as:

/api/auth/session

No corresponding request appears in the browser's DevTools network panel.

This is particularly unexpected because the issue is not limited to an incorrect response or an unexpected value from the authentication API—the expected client-side execution and network request do not occur at all.

Investigation Findings

So far, the investigation has identified the following:

  • TanStack Start server functions are correctly registered.
  • Server functions are executed successfully.
  • Server functions unexpectedly return undefined to the caller.
  • Updating TanStack dependencies to their latest versions did not resolve the issue.
  • The issue is not isolated to the custom TanStack Start server functions.
  • Native React useEffect behavior is also affected.
  • authClient requests are not being triggered.
  • Expected authentication requests, such as /api/auth/session, are not visible in the browser network panel.

Because both the server-side and client-side behavior are affected, the root cause is still unclear and may involve the TanStack Start environment, dependency configuration, bundling, or the interaction between the framework and the integration package.

Warning

This PR is intentionally kept as draft until the root cause of these issues is identified and the affected behavior is fixed.

Further investigation is required before this integration can be considered stable and ready for merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant