TanStackT
TanStack2y ago
3 replies
ordinary-sapphire

How to show loader while auth is verifying?

Version: react-router v1.31.20

I have a route /auth/verify which is navigated to when a user clicks on a magic link. The logic in the beforeLoad handles the magic link being clicked and verifies the user/creates a session and then redirects to the dashboard. While this is happening it shows a white page.

I would like to show a loading spinner or similar, but nothing I have tried works. Namely pendingComponent, a loader or component.

Any suggestions would be appreciated!

import { createFileRoute, redirect } from '@tanstack/react-router';
import { toast } from 'sonner';
import {
  handleMagicLinkClicked,
  isThisSameBrowserAndDevice,
} from '../utils/auth';

export const Route = createFileRoute('/auth/verify')({
  beforeLoad: async ({ navigate }) => {
    const startTime = Date.now();
    // Ensure it's the same browser and device that initiated the request
    const isSameBrowserAndDevice = await isThisSameBrowserAndDevice();
    if (!isSameBrowserAndDevice) {
      toast.error(
        'Please use the same device and browser that was used to request the link.'
      );
      throw redirect({ to: '/auth' });
    }

    // Handle the magic link click, which should perform the verification
    const result = await handleMagicLinkClicked();
    const duration = Date.now() - startTime; // Calculate duration
    console.log(
      `Magic link verification result: ${result} after ${duration} ms`
    );

    // If the result indicates success, recheck the auth status
    if (result === 'success') {
      navigate({ to: '/' }); // Redirect to a default or intended page
    } else {
      toast.error('Invalid or expired magic link');
      throw redirect({ to: '/auth' }); // Redirect back to login on failure
    }
  },
});
Was this page helpful?