Next.js Quickstart
Add authentication to your Next.js application in 5 minutes using the @syauth/nextjs SDK.
Before You Begin
You need these credentials before starting. Get them from the SyAuth Dashboard.
| What You Need | Where to Find It | Example |
|---|---|---|
| Client ID | Dashboard → OAuth Clients → Your App | a1b2c3d4-5678-90ab-cdef-... |
| API Key | Dashboard → API Keys | xxxxxxxxxxxxx |
New to SyAuth? Follow these steps first:
- Create a Nexorix account (SyAuth uses Nexorix for authentication)
- Create your first Application to get your credentials
- Add
http://localhost:3000/auth/callbackas 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
Where to find these values:
- Log in to syauth.com/dashboard
- Select your Workspace
- Click OAuth Clients in the sidebar
- Click on your application
- Copy the Client ID
To get an API Key:
- Click API Keys in the sidebar
- Click Create API Key
- Copy the key immediately (it's shown only once!)
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:
- Extracts the authorization code from the URL
- Exchanges it for access tokens
- Stores the tokens securely
- 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
| Value | Type | Description |
|---|---|---|
user | object | null | The authenticated user's profile data |
isAuthenticated | boolean | true if user is logged in |
isLoading | boolean | true while checking authentication status |
loginWithRedirect | function | Redirects user to SyAuth login page |
logout | function | Logs out the user and clears tokens |
User Object Properties
| Property | Type | Description |
|---|---|---|
id | string | Unique user identifier (UUID) |
email | string | User's email address |
first_name | string | User's first name |
last_name | string | User's last name |
email_verified | boolean | Whether 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
-
Start your development server:
npm run dev -
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:
- Check your
.env.localfile has this variable set - Restart your development server (
npm run dev)
"Invalid redirect_uri"
Cause: The redirect URI in your environment doesn't match your Dashboard configuration.
Fix:
- Go to Dashboard → OAuth Clients → Your App → Redirect URIs
- Ensure
http://localhost:3000/auth/callbackis listed - 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:
- Verify you have
/src/app/auth/callback/page.tsx - Ensure it uses the
useOAuthCallback()hook - 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:
- Double-check all variable names start with
NEXT_PUBLIC_ - Restart your dev server after changing
.env.local
Next Steps
- Create Your First Application — Set up your OAuth client in the Dashboard
- Key Concepts — Learn about Workspaces, OAuth Clients, and Users
- SDK Overview — SDK information
- Customizing the Login Page (in your Dashboard) — Brand the login experience