Authentication
Authentication in VEF mainly involves three parts:
createApiClient()manages tokens and refresh logiccreateLoginRouteOptions()defines the login routecreateLayoutRouteOptions()protects authenticated application areas
Wiring the Login Page
import { createFileRoute } from "@tanstack/react-router";
import { createLoginRouteOptions, LOGIN_ROUTE_ID } from "@vef-framework-react/starter";
import { apiClient } from "../../api";
import { login } from "../../apis/auth";
export const Route = createFileRoute(LOGIN_ROUTE_ID)(
createLoginRouteOptions({
onLogin: params => apiClient.executeMutation({ mutationFn: login, params })
})
);
What Happens After Login Succeeds
The built-in Login component from starter performs the following steps after onLogin succeeds:
- writes authenticated state into
useAppStore - stores tokens
- invalidates the router
- navigates to
redirector the index route - shows a success notification
Token Refresh
This is one of the key parts of createApiClient() configuration:
const apiClient = createApiClient({
http: {
baseUrl: "/api",
tokenExpiredCode: 1002,
async refreshToken(tokens) {
return await apiClient.executeMutation({
mutationFn: refreshAuth,
params: tokens
});
}
}
});
Logout
The remote logout action is typically implemented as a mutation and passed into the layout route through onLogout:
async function handleLogout() {
await apiClient.executeMutation({
mutationFn: logout
});
}
Client-side logout cleanup is then handled through handleClientLogout() and the router event chain.
Recommended Usage
- use
executeMutation()for login and token refresh - avoid introducing a separate store for authentication state
- keep route protection in the layout layer instead of repeating it on every page