Skip to main content

Next.js Quickstart

Add authentication to your Next.js application in 5 minutes using the @syauth/nextjs SDK.


Before You Begin

info

You need these credentials before starting. Get them from the SyAuth Dashboard.

What You NeedWhere to Find ItExample
Client IDDashboard → OAuth Clients → Your Appa1b2c3d4-5678-90ab-cdef-...
API KeyDashboard → API Keysxxxxxxxxxxxxx

New to SyAuth? Follow these steps first:

  1. Create a Nexorix account (SyAuth uses Nexorix for authentication)
  2. Create your first Application to get your credentials
  3. Add http://localhost:3000/auth/callback as a Redirect URI in your Application settings

Prerequisites

  • Node.js 18+ installed
  • A Next.js 14+ application (App Router)
  • A SyAuth account with an Application created

Step 1: Install the SDK

npm install @syauth/nextjs

The SDK handles all OAuth complexity for you: PKCE generation, token management, and automatic refresh.


Step 2: Configure Environment Variables

Create or update your .env.local file in your project root:

# Your SyAuth API URL (don't change this unless self-hosting)
NEXT_PUBLIC_SYAUTH_API_URL=https://api.syauth.com/e/v1

# Your Client ID from Dashboard → OAuth Clients → Your App
NEXT_PUBLIC_SYAUTH_CLIENT_ID=paste-your-client-id-here

# Where SyAuth redirects after login (must match Dashboard config!)
NEXT_PUBLIC_SYAUTH_REDIRECT_URI=http://localhost:3000/auth/callback

# Your API Key from Dashboard → API Keys
# Required only if you need user registration in your app (Create one if you haven't)
# IMPORTANT: API Keys are shown only once at creation. Store securely!
NEXT_PUBLIC_SYAUTH_API_KEY=paste-your-api-key-here
tip

Where to find these values:

  1. Log in to syauth.com/dashboard
  2. Select your Workspace
  3. Click OAuth Clients in the sidebar
  4. Click on your application
  5. Copy the Client ID

To get an API Key:

  1. Click API Keys in the sidebar
  2. Click Create API Key
  3. Copy the key immediately (it's shown only once!)
CAUTION

Make sure NEXT_PUBLIC_SYAUTH_REDIRECT_URI exactly matches the Redirect URI configured in your Application settings in the Dashboard. Even a trailing slash difference will cause errors!


Step 3: Wrap Your App with SyAuthProvider

Update your root layout to provide authentication context throughout your app:

// src/app/layout.tsx
import { SyAuthProvider } from '@syauth/nextjs';

export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<SyAuthProvider
config={{
apiUrl: process.env.NEXT_PUBLIC_SYAUTH_API_URL!,
oauthClientId: process.env.NEXT_PUBLIC_SYAUTH_CLIENT_ID!,
redirectUri: process.env.NEXT_PUBLIC_SYAUTH_REDIRECT_URI!,
apiKey: process.env.NEXT_PUBLIC_SYAUTH_API_KEY, // Optional
}}
>
{children}
</SyAuthProvider>
</body>
</html>
);
}

What this does: The SyAuthProvider makes authentication state (user, isAuthenticated, etc.) available to all components in your app.


Step 4: Create the OAuth Callback Page

When users log in, SyAuth redirects them back to your app. You need a page to handle this redirect:

// src/app/auth/callback/page.tsx
'use client';

import { useOAuthCallback } from '@syauth/nextjs';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';

export default function CallbackPage() {
const { loading, error, success } = useOAuthCallback();
const router = useRouter();

useEffect(() => {
if (success) {
// User is now authenticated! Redirect to your dashboard
router.push('/dashboard');
}
}, [success, router]);

if (loading) {
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<p>Authenticating...</p>
</div>
);
}

if (error) {
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '2rem' }}>
<h1>Authentication Failed</h1>
<p style={{ color: 'red' }}>{error}</p>
<button onClick={() => router.push('/')}>Go Back</button>
</div>
);
}

return <div>Redirecting...</div>;
}

What this does: The useOAuthCallback hook automatically:

  1. Extracts the authorization code from the URL
  2. Exchanges it for access tokens
  3. Stores the tokens securely
  4. Updates the authentication state

Step 5: Add Login and Protected Content

Now you can use the useSyAuth hook in any component:

// src/app/page.tsx
'use client';

import { useSyAuth } from '@syauth/nextjs';

export default function HomePage() {
const { user, isAuthenticated, isLoading, loginWithRedirect, logout } = useSyAuth();

// Show loading state while checking authentication
if (isLoading) {
return <div>Loading...</div>;
}

// User is not logged in - show login button
if (!isAuthenticated) {
return (
<div style={{ padding: '2rem' }}>
<h1>Welcome to My App</h1>
<p>Please sign in to continue.</p>
<button
onClick={() => loginWithRedirect()}
style={{ padding: '0.5rem 1rem', cursor: 'pointer' }}
>
Sign In with SyAuth
</button>
</div>
);
}

// User is logged in - show their profile
return (
<div style={{ padding: '2rem' }}>
<h1>Welcome, {user?.first_name}! 👋</h1>
<div style={{ marginBottom: '1rem' }}>
<p><strong>Email:</strong> {user?.email}</p>
<p><strong>Name:</strong> {user?.first_name} {user?.last_name}</p>
</div>
<button
onClick={() => logout()}
style={{ padding: '0.5rem 1rem', cursor: 'pointer' }}
>
Sign Out
</button>
</div>
);
}

Available Hook Values

ValueTypeDescription
userobject | nullThe authenticated user's profile data
isAuthenticatedbooleantrue if user is logged in
isLoadingbooleantrue while checking authentication status
loginWithRedirectfunctionRedirects user to SyAuth login page
logoutfunctionLogs out the user and clears tokens

User Object Properties

PropertyTypeDescription
idstringUnique user identifier (UUID)
emailstringUser's email address
first_namestringUser's first name
last_namestringUser's last name
email_verifiedbooleanWhether user's email is verified

Step 6: Protect Routes with Middleware (Optional)

To automatically redirect unauthenticated users away from protected pages:

// src/middleware.ts
import { withAuth } from '@syauth/nextjs/server';

export default withAuth({
// Routes that require authentication
protectedRoutes: ['/dashboard', '/profile', '/settings'],

// Where to redirect unauthenticated users
loginUrl: '/',

// Where to redirect after successful login
defaultProtectedRoute: '/dashboard',
});

export const config = {
// Apply middleware to all routes except static files
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};

What this does: When a user tries to access /dashboard without being logged in, they're automatically redirected to / (or your loginUrl).


Test Your Integration

  1. Start your development server:

    npm run dev
  2. Open http://localhost:3000

  3. Click "Sign In with SyAuth"

    • You'll be redirected to the SyAuth login page
    • Log in or create an account
    • You'll be redirected back to your app, now authenticated!

Done! 🎉

Your Next.js application now has:

  • ✅ OAuth 2.0 authentication with PKCE (secure!)
  • ✅ Automatic token refresh (no session timeouts)
  • ✅ Protected routes (optional middleware)
  • ✅ User session management
  • ✅ Login and logout functionality

Troubleshooting

"redirectUri is required"

Cause: The NEXT_PUBLIC_SYAUTH_REDIRECT_URI environment variable is missing or empty.

Fix:

  1. Check your .env.local file has this variable set
  2. Restart your development server (npm run dev)

"Invalid redirect_uri"

Cause: The redirect URI in your environment doesn't match your Dashboard configuration.

Fix:

  1. Go to Dashboard → OAuth Clients → Your App → Redirect URIs
  2. Ensure http://localhost:3000/auth/callback is listed
  3. Check for exact match (no extra slashes, correct port, etc.)

CORS Errors

Cause: Making direct API calls from the browser to SyAuth.

Fix: Always use loginWithRedirect() instead of making direct calls. The SDK handles authentication properly to avoid CORS issues.

"Not Authenticated After Redirect"

Cause: The callback page isn't processing the OAuth response correctly.

Fix:

  1. Verify you have /src/app/auth/callback/page.tsx
  2. Ensure it uses the useOAuthCallback() hook
  3. Make sure it's a client component ('use client' at the top)

Environment Variables Not Working

Cause: Next.js requires environment variables to start with NEXT_PUBLIC_ to be available in the browser.

Fix:

  1. Double-check all variable names start with NEXT_PUBLIC_
  2. Restart your dev server after changing .env.local

Next Steps