T
TanStack5mo ago
quickest-silver

Trouble with understanding useSession function from @tanstack/react-start-server

I am trying to implement auth with tanstack-start with react query. I followed basic auth starter example from the docs but I am getting this error:
Error adding information: TypeError: Cannot read properties of undefined (reading 'config')
at @tanstack_react-start_server.js?v=a2b44449:18409:34
at useAppSession (session.ts:11:19)
at getCurrentUserId (auth.ts:4:25)
at Object.addSomethingToUser [as mutationFn] (
Error adding information: TypeError: Cannot read properties of undefined (reading 'config')
at @tanstack_react-start_server.js?v=a2b44449:18409:34
at useAppSession (session.ts:11:19)
at getCurrentUserId (auth.ts:4:25)
at Object.addSomethingToUser [as mutationFn] (
When I log current session and userId, they are logged currently (inside getCurrentUserId function) Current setup looks like:
// utils/session.ts
import { User } from '@/types/user';
import { useSession } from '@tanstack/react-start/server';

type SessionUser = {
id: User['email'];
};

export function useAppSession() {
const password = import.meta.env.VITE_SESSION_SECRET;
return useSession<SessionUser>({
password,
});
}
// utils/session.ts
import { User } from '@/types/user';
import { useSession } from '@tanstack/react-start/server';

type SessionUser = {
id: User['email'];
};

export function useAppSession() {
const password = import.meta.env.VITE_SESSION_SECRET;
return useSession<SessionUser>({
password,
});
}
// utils/auth.ts
import { useAppSession } from './session';

export async function getCurrentUserId(): Promise<string> {
const session = await useAppSession();
if (!session.data.id) {
throw new Error('User not authenticated');
}
return session.data.id;
}
// utils/auth.ts
import { useAppSession } from './session';

export async function getCurrentUserId(): Promise<string> {
const session = await useAppSession();
if (!session.data.id) {
throw new Error('User not authenticated');
}
return session.data.id;
}
export async function addSomethingToUser(info) {
try {
const userId = await getCurrentUserId();
const currentInfo = await fetchInformation();
// use this userId to check permission and add the information
} catch (err) {
console.error('Error adding:', err);
}
}
export async function addSomethingToUser(info) {
try {
const userId = await getCurrentUserId();
const currentInfo = await fetchInformation();
// use this userId to check permission and add the information
} catch (err) {
console.error('Error adding:', err);
}
}
export async function fetchInformation(info) {
try {
const userId = await getCurrentUserId();
// use this userId to fetch the information
return information;
} catch (err) {
console.error('Error fetching:', err);
}
}
export async function fetchInformation(info) {
try {
const userId = await getCurrentUserId();
// use this userId to fetch the information
return information;
} catch (err) {
console.error('Error fetching:', err);
}
}
Any help would be really appreciated. Thanks!
5 Replies
quickest-silver
quickest-silverOP5mo ago
@Tanner Linsley
afraid-scarlet
afraid-scarlet5mo ago
Handle Session - h3
Remember your users using a session.
GitHub
router/packages/start-server-core/src/h3.ts at main · TanStack/router
🤖 Fully typesafe Router for React (and friends) w/ built-in caching, 1st class search-param APIs, client-side cache integration and isomorphic rendering. - TanStack/router
quickest-silver
quickest-silverOP5mo ago
@Jaga Santagostino So it means, tanstack start should handle this? Or am I missing something? In their basic-auth example, session is implemented in the same way I did. Docs doesn't mention anything about this. Do you have any idea what might be the issue and possible ways to resolve it?
protestant-coral
protestant-coral5mo ago
I think you're not supposed to use this in the client. It uses cookies to manage the session so it needs to be called server-side. Here's how I do it in my app:
import { createServerFn } from "@tanstack/react-start";
import { useAppSession } from "../session";

export const fetchSession = createServerFn({ method: "GET" }).handler(
async () => {
// We need to auth on the server so we have access to secure cookies
const session = await useAppSession();

return session.data;
},
);
import { createServerFn } from "@tanstack/react-start";
import { useAppSession } from "../session";

export const fetchSession = createServerFn({ method: "GET" }).handler(
async () => {
// We need to auth on the server so we have access to secure cookies
const session = await useAppSession();

return session.data;
},
);
Then I use it in my __root beforeLoad to add it to the global context
export const Route = createRootRouteWithContext<AppContext>()({
beforeLoad: async ({ location }) => {
const [session] = await Promise.all([
fetchSession(),
]);

return { session };
}
});
export const Route = createRootRouteWithContext<AppContext>()({
beforeLoad: async ({ location }) => {
const [session] = await Promise.all([
fetchSession(),
]);

return { session };
}
});
Then later in your app you can get it in your client code with the route context:
const { session } = Route.useRouteContext();
const { session } = Route.useRouteContext();
quickest-silver
quickest-silverOP5mo ago
thank you so much @Simon I really appreciate it.

Did you find this page helpful?