import { useEffect } from 'react';import { useRouter } from 'next/navigation';import { useStytchSession } from '@stytch/nextjs';import { LoginOrSignupForm } from "src/components/LoginOrSignupForm";export default function Login() { const { session, isInitialized } = useStytchSession(); const router = useRouter(); useEffect(() => { if (session && isInitialized) { router.replace("/home"); } }, [session, isInitialized, router]); if (!isInitialized || session) { return <p>Loading...</p>; } return <LoginOrSignupForm/>;}
If you’re using separate routes, add <LoginOrSignupForm> to your /authenticate redirect route as well, e.g. app/authenticate/page.jsx or pages/authenticate.jsx.
import { useEffect } from 'react';import { useRouter } from 'next/navigation';import { useStytchSession } from '@stytch/nextjs';import { LoginOrSignupForm } from "src/components/LoginOrSignupForm";export default function Login() { const { session, isInitialized } = useStytchSession(); const router = useRouter(); useEffect(() => { if (session && isInitialized) { router.replace("/home"); } }, [session, isInitialized, router]); if (!isInitialized || session) { return <p>Loading...</p>; } return <LoginOrSignupForm/>;}
If you’re using separate routes, add <LoginOrSignupForm> to your /authenticate redirect route as well, e.g. app/authenticate/page.jsx or pages/authenticate.jsx.
In your React app, run the command to install the SDK:
npm
npm install @stytch/react --save
3
Wrap your application in <StytchProvider>
Initialize the Stytch UI client through createStytchClient().
Pass the Stytch UI client to the <StytchProvider> component at the root of your application, making it accessible to all child components.
import { createStytchClient, StytchProvider } from '@stytch/react';const stytch = createStytchClient($YOUR_PUBLIC_KEY);// Add the component at the root of your applicationexport function App() { return ( <StytchProvider stytch={stytch}> {/* Your app code */} </StytchProvider> );}
4
Add <StytchLogin> UI component
Create a <StytchLogin> component.
Set authentication methods and relevant options in the config object.
If you’re using separate routes, add <stytch-ui> on your /authenticate redirect route as well, e.g. authenticate.html.
Handle session and user data
At this point, you can retrieve Session data and User data via the SDK. For example, useStytchSession() lets you retrieve the current session and can be used to determine if a user is already logged in.