You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Preface:
I'm trying to handle authentication on my front-end using TanStack Start and TanStack Router, protected routes, user data, etc. I am running my own Node.JS back-end that, when authenticates a user, sets two HttpOnly cookies (refresh token and access token).
I'd like to be able to have protected routes and know which user is currently logged in in my front-end, however, I'm not sure what the correct approach might be. I'd like to be able to utilize the beforeLoad() functionality, but I've not found a solution that will allow me to use it. I've tried using a React context (an auth context), and I've tried using server functions provided by TanStack Start.
When trying to use a context, I run into the issue where I can't properly set the context so that it is usable in a beforeLoad(). And the problem I've found when using server functions is that I am relying on cookies provided by my back-end, which in turn seems to cause issues. I may very well be missing some info/part/code that would solve it, but so far I've found no solution.
// src/contexts/AuthContext.tsximport{Loader}from"@mantine/core";import{createContext,typeReactNode,useContext,useEffect,useState,}from"react";import{BASE_URL_LOCAL}from"../helpers";exportinterfaceAuthContext{
user: User|null;
isLoading: boolean;
login: (email: string,password: string)=>Promise<void>;}typeBaseResponse<T>={status: string;
data: T;};typeUser={id: string;
email: string;
firstName: string;};constAuthContext=createContext<AuthContext|null>(null);exportconstAuthProvider=({ children }: {children: ReactNode})=>{const[user,setUser]=useState<User|null>(null);const[isLoading,setIsLoading]=useState<boolean>(true);useEffect(()=>{constinitializeAuth=async()=>{try{constresponse=awaitfetch(`${BASE_URL_LOCAL}/auth/refresh`,{method: "GET",credentials: "include",});if(!response.ok){thrownewError("Failed to refresh access token.");}constresult=(awaitresponse.json())asBaseResponse<User>;setUser(result.data);setIsLoading(false);}catch(error){setUser(null);}finally{setIsLoading(false);}};initializeAuth();},[]);constlogin=async(email: string,password: string)=>{constresponse=awaitfetch(`${BASE_URL_LOCAL}/auth/login`,{method: "POST",body: JSON.stringify({
email,
password,}),credentials: "include",});if(!response.ok){return;}constresult=(awaitresponse.json())asBaseResponse<User>;setUser(result.data);};constvalue: AuthContext={
user,
isLoading,
login,};// if (isLoading) {// return <Loader />;// }return<AuthContext.Providervalue={value}>{children}</AuthContext.Provider>;};exportconstuseAuth=()=>{constcontext=useContext(AuthContext);if(!context){thrownewError("useAuth must be used within an AuthProvider.");}returncontext;};
// src/routes/index.tsxexportconstRoute=createFileRoute("/")({beforeLoad: async()=>{// Where I'd like access to user/auth, for example.},component: Home,});
Open for any ideas!
PS. I'm very much still learning, and some of these things are new to me.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
Preface:
I'm trying to handle authentication on my front-end using TanStack Start and TanStack Router, protected routes, user data, etc. I am running my own Node.JS back-end that, when authenticates a user, sets two HttpOnly cookies (refresh token and access token).
I'd like to be able to have protected routes and know which user is currently logged in in my front-end, however, I'm not sure what the correct approach might be. I'd like to be able to utilize the
beforeLoad()functionality, but I've not found a solution that will allow me to use it. I've tried using a React context (an auth context), and I've tried using server functions provided by TanStack Start.When trying to use a context, I run into the issue where I can't properly set the context so that it is usable in a
beforeLoad(). And the problem I've found when using server functions is that I am relying on cookies provided by my back-end, which in turn seems to cause issues. I may very well be missing some info/part/code that would solve it, but so far I've found no solution.Open for any ideas!
PS. I'm very much still learning, and some of these things are new to me.
Beta Was this translation helpful? Give feedback.
All reactions