feat(tanstack-start): Add Tanstack Start integration package - #255
feat(tanstack-start): Add Tanstack Start integration package#255halvaradop wants to merge 5 commits into
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Important Review skippedDraft detected. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughAdds 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. ChangesTanStack Start authentication
Integration exports and generated output
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
Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (1)
packages/tanstack-start/src/lib/api.ts (1)
139-148: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the unreferenced test server function.
This handler is not returned by
apiand 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
⛔ Files ignored due to path filters (3)
bun.lockis excluded by!**/*.lockdeno.lockis excluded by!**/*.lockpnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (13)
apps/tanstack-start/src/routeTree.gen.tspackages/integration/deno.jsonpackages/integration/package.jsonpackages/tanstack-start/CHANGELOG.mdpackages/tanstack-start/README.mdpackages/tanstack-start/deno.jsonpackages/tanstack-start/package.jsonpackages/tanstack-start/src/@types/index.tspackages/tanstack-start/src/createAuth.tspackages/tanstack-start/src/index.tspackages/tanstack-start/src/lib/api.tspackages/tanstack-start/tsconfig.jsonpackages/tanstack-start/tsdown.config.ts
| const { headers: _h, toResponse: _t, ...spread } = output | ||
| return spread |
There was a problem hiding this comment.
🎯 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' || trueRepository: 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 || trueRepository: 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:
- 1: https://tanstack.com/start/latest/docs/framework/react/guide/server-functions
- 2: https://github.com/TanStack/router/blob/main/packages/start-server-core/skills/start-server-core/SKILL.md
- 3: https://unpkg.com/@tanstack/start-client-core@1.170.12/skills/start-core/server-functions/SKILL.md
🌐 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:
- 1: https://tanstack.com/start/latest/docs/framework/react/guide/server-functions
- 2: https://github.com/TanStack/router/blob/main/packages/start-server-core/skills/start-server-core/SKILL.md
- 3: https://github.com/TanStack/router/blob/a4154714/packages/start-server-core/src/request-response.ts
🌐 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:
- 1: feat(packages): enhance API type definitions and response structures #146
- 2: https://aura-stack-auth.vercel.app/docs/guides/integration
- 3: https://aura-stack-auth.vercel.app/docs/integrations/tanstack-start
- 4: https://github.com/TanStack/router/blob/main/packages/start-server-core/skills/start-server-core/SKILL.md
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.
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (2)
bun.lockis excluded by!**/*.lockpnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (38)
apps/tanstack-start/package.jsonapps/tanstack-start/src/components/header.tsxapps/tanstack-start/src/contexts/auth.tsxapps/tanstack-start/src/lib/auth-client.tsapps/tanstack-start/src/lib/auth-server.tsapps/tanstack-start/src/lib/auth.tsapps/tanstack-start/src/routes/api/auth.$.tsapps/tanstack-start/src/routes/client.tsxapps/tanstack-start/src/routes/server.tsxpackages/integration/package.jsonpackages/integration/tsdown.config.tspackages/tanstack-start/README.mdpackages/tanstack-start/package.jsonpackages/tanstack-start/src/@types/api.tspackages/tanstack-start/src/@types/core.tspackages/tanstack-start/src/@types/index.tspackages/tanstack-start/src/client.tsxpackages/tanstack-start/src/context.tsxpackages/tanstack-start/src/createAuth.tspackages/tanstack-start/src/index.tspackages/tanstack-start/src/lib/api.tspackages/tanstack-start/test/api/disconnectProvider.test.tspackages/tanstack-start/test/api/getAccessToken.test.tspackages/tanstack-start/test/api/getProviderTokens.test.tspackages/tanstack-start/test/api/getSession.test.tspackages/tanstack-start/test/api/isProviderConnected.test.tspackages/tanstack-start/test/api/refreshUserInfo.test.tspackages/tanstack-start/test/api/revokeToken.test.tspackages/tanstack-start/test/api/signIn.test.tspackages/tanstack-start/test/api/signInCredentials.test.tspackages/tanstack-start/test/api/signOut.test.tspackages/tanstack-start/test/api/signUp.test.tspackages/tanstack-start/test/api/test-utils.tspackages/tanstack-start/test/api/updateSession.test.tspackages/tanstack-start/test/types.test-d.tspackages/tanstack-start/tsconfig.jsonpackages/tanstack-start/tsdown.config.tspackages/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"], |
There was a problem hiding this comment.
🎯 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.
| type RefreshUserInfo<Identity extends Identities> = OptionalFetcher< | ||
| undefined, | ||
| any, | ||
| Promise<{ | ||
| success: boolean | ||
| session: Session<FromShapeToObject<Identity>> | null | ||
| }> | ||
| > |
There was a problem hiding this comment.
🎯 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/testRepository: 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' packagesRepository: 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>() |
There was a problem hiding this comment.
🎯 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> | nullAlso 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.
| resolve: { | ||
| alias: { | ||
| "@": path.resolve(__dirname, "./src"), | ||
| "@test": path.resolve(__dirname, "./test"), | ||
| }, |
There was a problem hiding this comment.
🩺 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.jsonRepository: 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$' | sortRepository: 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:
- 1: Vitest incorrectly injects __dirname when type is module vitest-dev/vitest#2841
- 2:
yarn testdoes not pass onvitest run -r packages/renderer --passWithNoTestspodman-desktop/podman-desktop#591 - 3: NooryA/kill-port@66ba372
- 4: https://github.com/vitest-dev/vitest/blob/main/docs/config/index.md
- 5: https://raw.githubusercontent.com/vitest-dev/vitest/refs/heads/v3.1/docs/config/index.md
- 6: Fluently-Org/fluently@e03abc8
🌐 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:
- 1: https://typescriptworld.com/migrating-a-jest-suite-to-vitest-with-typescript-strict-mode
- 2: Vitest incorrectly injects __dirname when type is module vitest-dev/vitest#2841
- 3: correct type for
import { defineConfig } from 'vitest/config';with"type": "commonjs"vitest-dev/vitest#6129 - 4: https://vitest.dev/blog/vitest-4
- 5: https://vitest.dev/blog/vitest-4-1
- 6: https://github.com/vitest-dev/vitest/blob/413ec5e6fc0addb2216db6104228138f8027f392/docs/config/index.md
🏁 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)" || trueRepository: 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:
- 1: vitest-dev/vitest@v4.1.3...v4.1.4
- 2: https://newreleases.io/project/npm/vitest/release/4.1.4
- 3: https://tangled.org/vitest.dev/vitest/commit/ac04bac206f49d793e7277084f707aee718aa936
- 4: Vitest incorrectly injects __dirname when type is module vitest-dev/vitest#2841
- 5: "__dirname is not defined in ES module scope" in vite.config.js with module type in package.json vitejs/vite#6946
- 6: https://github.com/laststance/gitbox/blob/main/vitest.config.ts
- 7: [vite-node] Is it for running code that you would build with Vite and run in production? vitest-dev/vitest#5970
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.
|
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 As part of the investigation, I updated the TanStack dependencies to their latest versions, but the issues persisted. I also verified whether For example, even when returning simple values such as strings or booleans for testing purposes, the caller consistently receives export const testFunction = createServerFn().handler(() => {
console.log("Server function executed")
return "test"
})The function is executed correctly, but the returned value is unexpectedly Client-Side InvestigationI also investigated the client-side behavior independently of the TanStack Start server functions by using the native React primitives and the However, the same unexpected behavior occurs on the client side. A 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 FindingsSo far, the investigation has identified the following:
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. |
Description
This pull request introduces the
@aura-stack/tanstack-startintegration package, providing seamless Aura Auth integration for TanStack Start applications.The package is built on top of
@aura-stack/authand 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/reactto provide the authentication context and React hooks, while adding a TanStack Start-specific layer for server functions and framework integration.Key Changes
@aura-stack/reactfor the client-side authentication layer.@aura-stack/authfunctionality.Architecture
The integration is structured in layers:
@aura-stack/authprovides the core authentication functionality,@aura-stack/reacthandles the React client-side layer, and@aura-stack/tanstack-startadds 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:
@tanstack/react-router.apps/tanstack-startdemo application with a complete and useful example.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.