### Install Dependencies Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-login-template/NGROK.md Installs the necessary project dependencies using npm. ```bash npm install ``` -------------------------------- ### Clone and Navigate Project Directory (Bash) Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-login-template/README.md Clones the repository and changes the current directory to the Next.js login template example. This is the initial step for setting up the project. ```bash git clone cd nextjs-syauth/examples/nextjs-login-template ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-app-with-sdk/README.md Copies the example environment file to `.env.local` and instructs users to update it with their SyAuth API URL, client ID, and redirect URI. These variables are crucial for the SDK to communicate with the SyAuth backend. ```bash cp .env.example .env.local NEXT_PUBLIC_SYAUTH_API_URL=https://api.yourdomain.com/e/v1 NEXT_PUBLIC_SYAUTH_CLIENT_ID=your-oauth-client-id-here NEXT_PUBLIC_SYAUTH_REDIRECT_URI=http://localhost:3000/auth/callback ``` -------------------------------- ### Run Development Server (Bash) Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-login-template/README.md Starts the Next.js development server, allowing you to view and test the login template locally. The application will be accessible at http://localhost:3000. ```bash npm run dev ``` -------------------------------- ### Run Next.js with Ngrok Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-login-template/NGROK.md Starts the Next.js development server and creates a public ngrok tunnel. ```bash npm run dev:ngrok ``` -------------------------------- ### Manually Start Ngrok Tunnel Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-login-template/NGROK.md Manually starts an ngrok tunnel to forward requests to a local HTTPS server, useful for self-signed certificates. ```bash ngrok http https://localhost:3002 ``` -------------------------------- ### Install @syauth/nextjs Package Source: https://github.com/syauth/nextjs-syauth/blob/main/README.md Install the @syauth/nextjs package using npm. This is the first step to integrating OAuth 2.0 authentication into your Next.js application. ```bash npm install @syauth/nextjs ``` -------------------------------- ### Configure Environment Variables (Bash) Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-login-template/README.md Copies the example environment file to a new file named .env and instructs the user to edit it with their specific settings. This is crucial for connecting to the SyAuth API and defining basic configuration. ```bash cp .env.example .env # Edit .env with your settings ``` -------------------------------- ### Implement Login Button with useSyAuth Hook Source: https://github.com/syauth/nextjs-syauth/blob/main/README.md Use the useSyAuth hook in your React components to access authentication functions. This example shows how to create a button that initiates the login process using loginWithRedirect. ```tsx // src/app/page.tsx 'use client'; import { useSyAuth } from '@syauth/nextjs'; export default function HomePage() { const { loginWithRedirect } = useSyAuth(); return ; } ``` -------------------------------- ### TypeScript Types for SyAuth SDK in Next.js Source: https://context7.com/syauth/nextjs-syauth/llms.txt Showcases the comprehensive TypeScript support provided by the SyAuth SDK, including examples of type-safe profile updates and middleware configurations. This ensures type safety across your Next.js application. Imports from `@syauth/nextjs`. ```typescript import type { AuthUser, SyAuthConfig, RegisterData, ProfileUpdateData, PasswordUpdateData, PasswordResetConfirmData, OAuthCallbackParams, OAuthTokenResponse, VerificationResponse, PasswordResetResponse, UseOAuthCallbackResult, MiddlewareOptions, } from '@syauth/nextjs'; // Example: Type-safe profile update const updateUserProfile = async ( updateFn: (data: ProfileUpdateData) => Promise ): Promise => { const profileData: ProfileUpdateData = { first_name: 'John', last_name: 'Doe', company: 'Acme Inc', job_title: 'Software Engineer', phone_number: '+1234567890', country: 'United States', }; const updatedUser: AuthUser = await updateFn(profileData); console.log('Updated user:', updatedUser); }; // Example: Type-safe middleware options const middlewareConfig: MiddlewareOptions = { protectedRoutes: ['/dashboard', '/profile'], loginUrl: '/login', defaultProtectedRoute: '/dashboard', authCookieName: 'auth_status', authRoutes: ['/login', '/register', '/auth/callback'], }; ``` -------------------------------- ### Required Environment Variables (Bash) Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-login-template/README.md Lists the essential environment variables that must be configured for the SyAuth login template to function correctly. These include API URLs, client IDs, and login URLs. ```bash NEXT_PUBLIC_SYAUTH_API_URL=https://api.yourdomain.com/e/v1 NEXT_PUBLIC_SYAUTH_CLIENT_ID=your-oauth-client-id NEXT_PUBLIC_LOGIN_URL=https://login.yourdomain.com ``` -------------------------------- ### Wrap App with SyAuthProvider (TypeScript/React) Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-app-with-sdk/README.md Demonstrates how to wrap the root layout of a Next.js application with `SyAuthProvider` from the `@syauth/nextjs` SDK. This component initializes the authentication context for the entire application, using environment variables for configuration. ```tsx import { SyAuthProvider } from '@syauth/nextjs' export default function RootLayout({ children }) { return ( {children} ) } ``` -------------------------------- ### Configure Environment Variables for SyAuth Source: https://github.com/syauth/nextjs-syauth/blob/main/README.md Set up the necessary environment variables in your .env.local file to configure the SyAuth SDK. These include the API URL, client ID, and redirect URI for the OAuth flow. ```bash # .env.local NEXT_PUBLIC_SYAUTH_API_URL=https://api.yourdomain.com/e/v1 NEXT_PUBLIC_SYAUTH_CLIENT_ID=your-client-id NEXT_PUBLIC_SYAUTH_REDIRECT_URI=http://localhost:3000/auth/callback NEXT_PUBLIC_SYAUTH_API_KEY=your-api-key # Optional - required only for user registration ``` -------------------------------- ### Optional Branding Environment Variables (Bash) Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-login-template/README.md Details optional environment variables that can be set to override default branding elements such as company name, logo URL, and primary color. ```bash NEXT_PUBLIC_COMPANY_NAME=Acme Corporation NEXT_PUBLIC_LOGO_URL=https://yourdomain.com/logo.png NEXT_PUBLIC_PRIMARY_COLOR=#4F46E5 ``` -------------------------------- ### Initiate OAuth 2.0 Login Flow with loginWithRedirect Source: https://context7.com/syauth/nextjs-syauth/llms.txt Initiates the OAuth 2.0 authorization code flow with PKCE, redirecting the user to the authorization server. It handles the redirection back to the specified redirect URI and can accept a returnTo parameter to specify the post-login destination. ```tsx 'use client'; import { useSyAuth } from '@syauth/nextjs'; import { useSearchParams } from 'next/navigation'; export default function LoginPage() { const { loginWithRedirect, error } = useSyAuth(); const searchParams = useSearchParams(); const returnTo = searchParams.get('return_to'); const handleLogin = async () => { try { // Redirect to OAuth authorization server // Will automatically redirect back to NEXT_PUBLIC_SYAUTH_REDIRECT_URI await loginWithRedirect(returnTo || '/dashboard'); } catch (err) { console.error('Login failed:', err); } }; return (

Sign In

{error &&
{error}
}
); } ``` -------------------------------- ### Wrap Application with SyAuthProvider Source: https://github.com/syauth/nextjs-syauth/blob/main/README.md Wrap your Next.js application's root layout with the SyAuthProvider component to initialize the authentication context. Provide the configuration object with your environment variables and specify the redirect path after login. ```tsx // src/app/layout.tsx import { SyAuthProvider } from '@syauth/nextjs'; export default function RootLayout({ children }) { return ( {children} ); } ``` -------------------------------- ### Set Ngrok Authtoken Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-login-template/NGROK.md Sets the ngrok authentication token as an environment variable or in a .env.local file for secure tunneling. ```bash export NGROK_AUTH_TOKEN=your_ngrok_authtoken_here ``` ```env NGROK_AUTH_TOKEN=your_ngrok_authtoken_here ``` -------------------------------- ### Set Ngrok Authtoken (Bash) Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-app-with-sdk/NGROK.md Sets the ngrok authentication token as an environment variable. This is optional but recommended for ngrok usage. ```bash export NGROK_AUTH_TOKEN=your_ngrok_authtoken_here ``` -------------------------------- ### Register New User with useSyAuth Hook Source: https://github.com/syauth/nextjs-syauth/blob/main/README.md Demonstrates how to use the `register` function from the `useSyAuth` hook to create a new user account. It takes user details like email, password, first name, and last name as input. ```tsx const { register } = useSyAuth(); const handleRegister = async () => { await register({ email: 'user@example.com', password: 'securePassword123', first_name: 'John', last_name: 'Doe', }); // User created! Redirect to email verification }; ``` -------------------------------- ### Ngrok Authtoken in .env.local Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-app-with-sdk/NGROK.md Stores the ngrok authentication token in the .env.local file for persistent configuration. ```properties NGROK_AUTH_TOKEN=your_ngrok_authtoken_here ``` -------------------------------- ### loginWithRedirect - OAuth 2.0 Login Flow Source: https://context7.com/syauth/nextjs-syauth/llms.txt Initiates the OAuth 2.0 authorization code flow with PKCE, redirecting the user to the authorization server for authentication. ```APIDOC ## loginWithRedirect - OAuth 2.0 Login Flow ### Description Initiates OAuth 2.0 authorization code flow with PKCE, redirecting users to your authorization server. ### Usage ```tsx 'use client'; import { useSyAuth } from '@syauth/nextjs'; import { useSearchParams } from 'next/navigation'; export default function LoginPage() { const { loginWithRedirect, error } = useSyAuth(); const searchParams = useSearchParams(); const returnTo = searchParams.get('return_to'); const handleLogin = async () => { try { // Redirect to OAuth authorization server // Will automatically redirect back to NEXT_PUBLIC_SYAUTH_REDIRECT_URI await loginWithRedirect(returnTo || '/dashboard'); } catch (err) { console.error('Login failed:', err); } }; return (

Sign In

{error &&
{error}
}
); } ``` ### Method ```APIDOC loginWithRedirect(returnTo?: string): Promise ``` ### Parameters * **returnTo** (string) - Optional - The path to redirect to after successful login. If not provided, it uses the `redirectAfterLogin` configuration or defaults to '/'. ### Returns * **Promise** - A promise that resolves when the redirect is initiated. It may reject if there's an issue initiating the flow. ``` -------------------------------- ### Check Ngrok Server Accessibility Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-login-template/NGROK.md Tests if the ngrok tunnel can reach the local server, useful for troubleshooting connection issues. ```bash curl -k https://localhost:3002 ``` -------------------------------- ### SyAuth Environment Variables for Next.js Source: https://github.com/syauth/nextjs-syauth/blob/main/README.md Configure SyAuth authentication in a Next.js application by setting necessary environment variables. These variables define the API URL, OAuth client ID, redirect URI, and optionally an API key for user registration. Ensure the redirect URI matches your OAuth client configuration. ```bash NEXT_PUBLIC_SYAUTH_API_URL=https://api.yourdomain.com/e/v1 NEXT_PUBLIC_SYAUTH_CLIENT_ID=your-client-id NEXT_PUBLIC_SYAUTH_REDIRECT_URI=http://localhost:3000/auth/callback NEXT_PUBLIC_SYAUTH_API_KEY=your-api-key # Optional - required for user registration ``` -------------------------------- ### Import Server-Side Utilities from @syauth/nextjs/server Source: https://github.com/syauth/nextjs-syauth/blob/main/README.md Import server-side utilities from the '@syauth/nextjs/server' path. These utilities are intended for use in server-side contexts and will be available in future releases. ```tsx import { /* server utilities */ } from '@syauth/nextjs/server'; ``` -------------------------------- ### Customize Ngrok Tunnel Host Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-login-template/NGROK.md Runs the Next.js development server with ngrok, specifying a custom host for the tunnel. ```bash SERVER_HOST=127.0.0.1 npm run dev:ngrok ``` -------------------------------- ### Advanced Middleware with Custom Logic using Next.js Source: https://context7.com/syauth/nextjs-syauth/llms.txt Demonstrates an advanced middleware pattern in Next.js that allows for custom logic execution before SyAuth's authentication checks. It shows how to add custom logging and response headers. Requires `@syauth/nextjs/middleware`. ```typescript // src/middleware.ts import { NextRequest, NextResponse } from 'next/server'; import { withAuth } from '@syauth/nextjs/middleware'; export default function middleware(request: NextRequest) { // Custom logging console.log('Request path:', request.nextUrl.pathname); // Custom headers or checks const response = withAuth(request, { protectedRoutes: ['/dashboard', '/profile'], loginUrl: '/login', defaultProtectedRoute: '/dashboard', }); // Add custom response headers response.headers.set('X-Custom-Header', 'value'); return response; } export const config = { matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'], }; ``` -------------------------------- ### Run Next.js with Ngrok CLI Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-login-template/NGROK.md Executes a script to run the Next.js development server with ngrok CLI, specifically for handling HTTPS connections. ```bash ./scripts/start-with-ngrok-cli.sh ``` ```bash npm run dev:ngrok:cli ``` -------------------------------- ### SyAuthProvider - Application Wrapper Source: https://context7.com/syauth/nextjs-syauth/llms.txt The SyAuthProvider is a React context provider that must be placed at the root of your Next.js application to enable authentication features globally. ```APIDOC ## SyAuthProvider - Application Wrapper ### Description React context provider that wraps your Next.js application to enable authentication throughout your app. Must be placed at the root level to provide auth state to all child components. ### Usage ```tsx // src/app/layout.tsx import { SyAuthProvider } from '@syauth/nextjs'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` ### Configuration Options * **config** (object) - Required - Authentication configuration settings. * **apiUrl** (string) - Required - The base URL of your SyAuth API. * **oauthClientId** (string) - Required - Your OAuth 2.0 client ID. * **redirectUri** (string) - Required - The URI where users are redirected after authentication. * **apiKey** (string) - Optional - API key for registration or other operations. * **scopes** (string) - Optional - OAuth 2.0 scopes to request. * **redirectAfterLogin** (string) - Optional - The path to redirect to after successful login. Defaults to '/'. * **unauthorizedRedirect** (string) - Optional - The path to redirect to when a user is unauthorized. Defaults to '/login'. ``` -------------------------------- ### Configure SyAuthProvider for Next.js Application Source: https://context7.com/syauth/nextjs-syauth/llms.txt Wraps the Next.js application with SyAuthProvider to enable authentication context. It requires configuration for the API URL, client ID, redirect URI, and optionally an API key and scopes. This provider should be placed at the root of your application. ```tsx import { SyAuthProvider } from '@syauth/nextjs'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` -------------------------------- ### Use SyAuth SDK Hooks in Components (TypeScript/React) Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-app-with-sdk/README.md Shows how to use the `useSyAuth` hook within any React component to access authentication state and functions. It provides access to the user object, authentication status, and methods for signing in and out. ```tsx // In any component import { useSyAuth } from '@syauth/nextjs' export default function MyComponent() { const { user, isAuthenticated, loginWithRedirect, logout } = useSyAuth() if (!isAuthenticated) { return } return (

Welcome, {user.email}!

) } ``` -------------------------------- ### Implement Route Protection with withAuth Middleware Source: https://github.com/syauth/nextjs-syauth/blob/main/README.md Use the `withAuth` helper from '@syauth/nextjs/middleware' to protect specific routes in your Next.js application. Configure protected routes, login URL, and default protected route for redirection. ```tsx // src/middleware.ts import { withAuth } from '@syauth/nextjs/middleware'; export default withAuth({ protectedRoutes: ['/dashboard', '/profile'], loginUrl: '/', defaultProtectedRoute: '/dashboard', }); export const config = { matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'], }; ``` -------------------------------- ### Customize Ngrok Tunnel Port Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-login-template/NGROK.md Runs the Next.js development server with ngrok, overriding the default port. ```bash PORT=3003 npm run dev:ngrok ``` -------------------------------- ### Import Client-Side Exports from @syauth/nextjs Source: https://github.com/syauth/nextjs-syauth/blob/main/README.md Import necessary components and hooks for client-side authentication from the main '@syauth/nextjs' package. This includes the provider, auth hooks, and the SyAuth class. ```tsx import { SyAuthProvider, useSyAuth, useOAuthCallback, SyAuth } from '@syauth/nextjs'; ``` -------------------------------- ### withAuth Middleware for Route Protection Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-app-with-sdk/README.md The `withAuth` middleware is used to protect specific routes within a Next.js application. It allows configuration of protected routes, a default redirect destination after login, and the URL for unauthenticated users to be redirected to. ```tsx withAuth({ protectedRoutes: ['/dashboard', '/profile'], defaultProtectedRoute: '/dashboard', loginUrl: '/', }) ``` -------------------------------- ### Handle OAuth Callback with useOAuthCallback Hook Source: https://github.com/syauth/nextjs-syauth/blob/main/README.md Create a callback page to handle the response from the OAuth provider using the useOAuthCallback hook. This hook manages the loading and error states during the authentication callback process. ```tsx // src/app/auth/callback/page.tsx 'use client'; import { useOAuthCallback } from '@syauth/nextjs'; export default function CallbackPage() { const { loading, error } = useOAuthCallback(); if (loading) return
Authenticating...
; if (error) return
Error: {error}
; return
Success!
; } ``` -------------------------------- ### Protect Routes with Middleware (TypeScript) Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-app-with-sdk/README.md Defines middleware using the `withAuth` function from `@syauth/nextjs` to protect specific routes within the Next.js application. It allows configuration of protected routes, a default redirect route, and the login URL. ```ts // src/middleware.ts import { withAuth } from '@syauth/nextjs' export default withAuth({ protectedRoutes: ['/dashboard', '/profile'], defaultProtectedRoute: '/dashboard', loginUrl: '/', }) ``` -------------------------------- ### useOAuthCallback Hook for OAuth Flow Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-app-with-sdk/README.md The `useOAuthCallback` hook is designed to manage the post-authentication callback process. It indicates the loading state during callback processing, any errors encountered, and a success flag upon completion. ```tsx const { loading, error, success, } = useOAuthCallback() ``` -------------------------------- ### User Registration with useSyAuth Hook (Next.js) Source: https://context7.com/syauth/nextjs-syauth/llms.txt The `register` function within the `useSyAuth` hook facilitates user registration by creating a new account. It includes a basic form for collecting user credentials and initiates an email verification workflow upon successful registration. Error handling and loading states are managed. ```tsx 'use client'; import { useSyAuth } from '@syauth/nextjs'; import { useState } from 'react'; export default function RegisterPage() { const { register, error, loading } = useSyAuth(); const [formData, setFormData] = useState({ email: '', password: '', confirm_password: '', first_name: '', last_name: '', }); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); try { await register({ ...formData, oauth_client: process.env.NEXT_PUBLIC_SYAUTH_CLIENT_ID!, }); // Automatically redirects to /verify-email?email=...®istered=true } catch (err) { console.error('Registration failed:', err); } }; return (

Create Account

{error &&
{error}
} setFormData({ ...formData, email: e.target.value })} required /> setFormData({ ...formData, first_name: e.target.value })} required /> setFormData({ ...formData, last_name: e.target.value })} required /> setFormData({ ...formData, password: e.target.value })} required /> setFormData({ ...formData, confirm_password: e.target.value })} required />
); } ``` -------------------------------- ### Handle OAuth Callback (TypeScript/React) Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-app-with-sdk/README.md Implements the OAuth callback handler in a Next.js page component using the `useOAuthCallback` hook from the `@syauth/nextjs` SDK. This component manages the process of exchanging the authorization code for tokens after the user is redirected back from the SyAuth server. ```tsx // src/app/auth/callback/page.tsx 'use client' import { useOAuthCallback } from '@syauth/nextjs' export default function CallbackPage() { const { loading, error } = useOAuthCallback() if (loading) return
Processing...
if (error) return
Error: {error}
return
Success! Redirecting...
} ``` -------------------------------- ### Manual Token Refresh with SyAuth Client Source: https://github.com/syauth/nextjs-syauth/blob/main/README.md Obtain a valid authentication token, automatically refreshing it if necessary, using the `getValidToken` method from the SyAuth client. This process ensures that API requests are made with an up-to-date token, and handles silent background refreshes or retries on 401 errors. ```tsx const { authClient } = useSyAuth(); // Get a valid token (auto-refreshes if needed) const token = await authClient.getValidToken(); ``` -------------------------------- ### useSyAuth Hook for Authentication State Source: https://github.com/syauth/nextjs-syauth/blob/main/examples/nextjs-app-with-sdk/README.md The `useSyAuth` hook provides access to authentication status, user data, and authentication actions. It returns the current user object, authentication status, loading and error states, the auth client instance, and functions for login, logout, and profile updates. ```tsx const { user, isAuthenticated, loading, error, authClient, loginWithRedirect, logout, updateProfile, } = useSyAuth() ``` -------------------------------- ### Custom Next.js Middleware with SyAuth Source: https://github.com/syauth/nextjs-syauth/blob/main/README.md Implement custom authentication logic in Next.js middleware using the `withAuth` higher-order component from `@syauth/nextjs/middleware`. This allows for protected routes, custom login URLs, and default protected route handling. Middleware runs in the Edge Runtime and does not support React hooks. ```tsx // src/middleware.ts import { NextRequest } from 'next/server'; import { withAuth } from '@syauth/nextjs/middleware'; export default function middleware(request: NextRequest) { // Add custom logic here if needed return withAuth(request, { protectedRoutes: ['/dashboard', '/profile'], loginUrl: '/', defaultProtectedRoute: '/dashboard', }); } ``` -------------------------------- ### Route Protection with SyAuth Next.js Middleware Source: https://context7.com/syauth/nextjs-syauth/llms.txt Implements route protection for Next.js applications using SyAuth middleware. This middleware runs in the Edge Runtime and can be configured with protected routes, login URL, default redirect, and authentication cookie name. It defines which routes are protected and how unauthenticated users are handled. ```typescript // src/middleware.ts import { withAuth } from '@syauth/nextjs/middleware'; export default withAuth({ protectedRoutes: ['/dashboard', '/profile', '/settings', '/account'], loginUrl: '/login', defaultProtectedRoute: '/dashboard', authCookieName: 'auth_status', // Optional - default: 'auth_status' authRoutes: [ // Optional - default includes these '/login', '/register', '/forgot-password', '/reset-password', '/verify-email', '/auth/callback', ], }); export const config = { matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'], }; ``` -------------------------------- ### TypeScript Types for SyAuth SDK Source: https://github.com/syauth/nextjs-syauth/blob/main/README.md Utilize TypeScript for type safety when integrating the SyAuth SDK in your Next.js application. Import various types for authentication, configuration, registration data, and OAuth callback handling for both client-side and middleware usage. ```tsx // Client types import type { AuthUser, SyAuthConfig, RegisterData, OAuthCallbackParams, UseOAuthCallbackResult, } from '@syauth/nextjs'; // Middleware types import type { MiddlewareOptions } from '@syauth/nextjs/middleware'; ``` -------------------------------- ### Import Middleware Export from @syauth/nextjs/middleware Source: https://github.com/syauth/nextjs-syauth/blob/main/README.md Import the `withAuth` function from the '@syauth/nextjs/middleware' path for use in Next.js Edge Runtime middleware. This allows for server-side route protection without React dependencies. ```tsx import { withAuth } from '@syauth/nextjs/middleware'; ``` -------------------------------- ### useSyAuth Hook - Authentication State and Methods Source: https://context7.com/syauth/nextjs-syauth/llms.txt The useSyAuth hook provides access to the current authentication state, user information, and authentication methods within your React components. ```APIDOC ## useSyAuth Hook - Authentication State and Methods ### Description Primary React hook for accessing authentication state and methods throughout your application. ### Usage ```tsx 'use client'; import { useSyAuth } from '@syauth/nextjs'; export default function DashboardPage() { const { user, isAuthenticated, loading, loginWithRedirect, logout } = useSyAuth(); if (loading) { return
Loading authentication...
; } if (!isAuthenticated) { return (

Welcome

); } return (

Dashboard

Welcome, {user?.email}

Name: {user?.first_name} {user?.last_name}

Email Verified: {user?.email_verified ? 'Yes' : 'No'}

); } ``` ### Returned Values * **user** (object | null) - The authenticated user's profile information, or null if not authenticated. * **isAuthenticated** (boolean) - True if the user is currently authenticated, false otherwise. * **loading** (boolean) - True while the authentication state is being determined, false otherwise. * **loginWithRedirect** (function) - A function that initiates the OAuth 2.0 login flow. * **logout** (function) - A function that logs the user out. ``` -------------------------------- ### Automatic Token Refresh and Retry Logic in Next.js Source: https://context7.com/syauth/nextjs-syauth/llms.txt Illustrates how the SyAuth SDK automatically handles token refreshes and retries requests with a 401 error using the `useSyAuth` hook in a Next.js client component. It ensures data fetching with a valid token. Depends on `@syauth/nextjs`. ```tsx 'use client'; import { useSyAuth } from '@syauth/nextjs'; import { useEffect, useState } from 'react'; export default function ProtectedDataPage() { const { authClient, isAuthenticated } = useSyAuth(); const [data, setData] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const fetchProtectedData = async () => { if (!isAuthenticated) return; try { // authClient automatically: // 1. Checks if token is expired (within 5 min buffer) // 2. Refreshes token if needed before request // 3. Retries request if it receives 401 error // 4. Logs user out if refresh fails const token = await authClient.getValidToken(); const response = await fetch('https://api.example.com/protected-data', { headers: { 'Authorization': `Bearer ${token}`, }, }); if (response.ok) { const result = await response.json(); setData(result); } } catch (error) { console.error('Failed to fetch data:', error); } finally { setLoading(false); } }; fetchProtectedData(); }, [authClient, isAuthenticated]); if (loading) return
Loading...
; if (!data) return
No data available
; return (

Protected Data

{JSON.stringify(data, null, 2)}
); } ``` -------------------------------- ### Email Verification with useSyAuth Hook (Next.js) Source: https://context7.com/syauth/nextjs-syauth/llms.txt The `verifyEmail` and `requestVerificationCode` functions from the `useSyAuth` hook manage the email verification process. Users can enter a code sent to their email to verify their account, or request a new code if needed. The hook handles the verification logic and provides feedback on success or failure. ```tsx 'use client'; import { useSyAuth } from '@syauth/nextjs'; import { useState } from 'react'; import { useSearchParams } from 'next/navigation'; export default function VerifyEmailPage() { const { verifyEmail, requestVerificationCode, loading, error } = useSyAuth(); const searchParams = useSearchParams(); const email = searchParams.get('email') || ''; const [code, setCode] = useState(''); const handleVerify = async (e: React.FormEvent) => { e.preventDefault(); try { await verifyEmail(email, code); // Automatically redirects to /login?verified=true&email=... } catch (err) { console.error('Verification failed:', err); } }; const handleResendCode = async () => { try { await requestVerificationCode(email); alert('Verification code sent! Check your email.'); } catch (err) { console.error('Failed to resend code:', err); } }; return (

Verify Your Email

We sent a verification code to {email}

{error &&
{error}
}
setCode(e.target.value)} maxLength={6} required />
); } ``` -------------------------------- ### Access Authentication State with useSyAuth Hook Source: https://context7.com/syauth/nextjs-syauth/llms.txt The useSyAuth hook provides access to user authentication state, loading status, and authentication methods like login and logout. It's essential for managing user sessions and UI states based on authentication status. ```tsx 'use client'; import { useSyAuth } from '@syauth/nextjs'; export default function DashboardPage() { const { user, isAuthenticated, loading, loginWithRedirect, logout } = useSyAuth(); if (loading) { return
Loading authentication...
; } if (!isAuthenticated) { return (

Welcome

); } return (

Dashboard

Welcome, {user?.email}

Name: {user?.first_name} {user?.last_name}

Email Verified: {user?.email_verified ? 'Yes' : 'No'}

); } ``` -------------------------------- ### Update User Profile with SyAuth Next.js Source: https://context7.com/syauth/nextjs-syauth/llms.txt Allows users to update their profile information such as name, company, and job title. It utilizes the `useSyAuth` hook from '@syauth/nextjs' to fetch user data and the `updateProfile` function to persist changes. The component includes form handling, state management for form data and success/error messages, and real-time updates to the form fields based on the current user data. ```tsx 'use client'; import { useSyAuth } from '@syauth/nextjs'; import { useState, useEffect } from 'react'; export default function ProfilePage() { const { user, updateProfile, loading, error } = useSyAuth(); const [formData, setFormData] = useState({ first_name: '', last_name: '', company: '', job_title: '', phone_number: '', country: '', }); const [success, setSuccess] = useState(false); useEffect(() => { if (user) { setFormData({ first_name: user.first_name || '', last_name: user.last_name || '', company: user.company || '', job_title: user.job_title || '', phone_number: user.phone_number || '', country: user.country || '', }); } }, [user]); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setSuccess(false); try { await updateProfile(formData); setSuccess(true); setTimeout(() => setSuccess(false), 3000); } catch (err) { console.error('Profile update failed:', err); } }; return (

Update Profile

{error &&
{error}
} {success &&
Profile updated successfully!
} setFormData({ ...formData, first_name: e.target.value })} /> setFormData({ ...formData, last_name: e.target.value })} /> setFormData({ ...formData, company: e.target.value })} /> setFormData({ ...formData, job_title: e.target.value })} /> setFormData({ ...formData, phone_number: e.target.value })} /> setFormData({ ...formData, country: e.target.value })} />
); } ``` -------------------------------- ### Confirm Password Reset with SyAuth Next.js Source: https://context7.com/syauth/nextjs-syauth/llms.txt Completes the password reset process using the code received via email and the new password. This component uses `useSyAuth` and `useSearchParams` to retrieve the email from the URL, manages form state for email, code, and passwords, and includes a password confirmation check. ```tsx 'use client'; import { useSyAuth } from '@syauth/nextjs'; import { useState } from 'react'; import { useSearchParams } from 'next/navigation'; export default function ResetPasswordPage() { const { confirmPasswordReset, loading, error } = useSyAuth(); const searchParams = useSearchParams(); const emailParam = searchParams.get('email') || ''; const [formData, setFormData] = useState({ email: emailParam, code: '', new_password: '', confirm_password: '', }); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (formData.new_password !== formData.confirm_password) { alert('Passwords do not match'); return; } try { await confirmPasswordReset(formData); // Automatically redirects to /login?reset=true&email=... } catch (err) { console.error('Password reset failed:', err); } }; return (

Reset Password

Enter the code sent to your email and your new password.

{error &&
{error}
} setFormData({ ...formData, email: e.target.value })} required /> setFormData({ ...formData, code: e.target.value })} maxLength={6} required /> setFormData({ ...formData, new_password: e.target.value })} required /> setFormData({ ...formData, confirm_password: e.target.value })} required />
); } ``` -------------------------------- ### Request Password Reset with SyAuth Next.js Source: https://context7.com/syauth/nextjs-syauth/llms.txt Initiates the password reset process by sending a reset code to the user's email. It utilizes the `useSyAuth` hook from '@syauth/nextjs' and handles form submission, state management for email input, and displays loading/error states. ```tsx 'use client'; import { useSyAuth } from '@syauth/nextjs'; import { useState } from 'react'; export default function ForgotPasswordPage() { const { requestPasswordReset, loading, error } = useSyAuth(); const [email, setEmail] = useState(''); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); try { await requestPasswordReset(email); // Automatically redirects to /reset-password?email=... } catch (err) { console.error('Password reset request failed:', err); } }; return (

Forgot Password

Enter your email address and we'll send you a reset code.

{error &&
{error}
} setEmail(e.target.value)} required /> Back to Login
); } ```