Blog>
Snippets

Integrating Third-Party Authentication Services

Provide a code snippet showing how to integrate a third-party authentication service (like Auth0) with TanStack Router for handling authenticated routes.
import { Auth0Provider } from '@auth0/auth0-react';
import { createBrowserRouter, RouterProvider } from '@tanstack/react-router';
import { YourComponent } from './YourComponent';
import { AuthWrapper } from './components/AuthWrapper';

// Define your router
const router = createBrowserRouter([
  {
    path: '/',
    element: <YourComponent />, // Public route
  },
  {
    path: '/protected',
    element: (
      <AuthWrapper>
        <YourProtectedComponent />
      </AuthWrapper>
    ), // Wrapped in AuthWrapper for protected routes
  },
]);

function App() {
  return (
    <Auth0Provider
      domain="YOUR_AUTH0_DOMAIN"
      clientId="YOUR_AUTH0_CLIENT_ID"
      redirectUri={window.location.origin}
    >
      <RouterProvider router={router} />
    </Auth0Provider>
  );
}
This code integrates Auth0 with TanStack Router for a JavaScript SPA. It sets up Auth0Provider with necessary details like domain and clientId, wraps the application routing with it, ensuring protected routes are accessible only after authentication. The AuthWrapper component handles the logic of checking if a user is authenticated, redirecting unauthenticated users to the login page, which is managed by Auth0.