
Neon Auth
- 226 installs
- 86 repo stars
- Updated June 2, 2026
- neondatabase/ai-rules
Wire Neon database authentication into app backends and serverless stacks following ai-rules patterns for secure connection strings, roles, and auth-aware queries.
About
Guides implementation of Neon database authentication per neondatabase ai-rules—covering connection setup, credential handling, and secure integration patterns so SaaS and API backends authenticate cleanly to Neon Postgres during build.
- Neon auth setup
- Secure DB connections
- Serverless Postgres
- Role-based access
- Backend integration patterns
Neon Auth by the numbers
- 226 all-time installs (skills.sh)
- +9 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #217 of 911 Databases skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/neondatabase/ai-rules --skill neon-authAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 226 |
|---|---|
| repo stars | ★ 86 |
| Last updated | June 2, 2026 |
| Repository | neondatabase/ai-rules ↗ |
What it does
Wire Neon database authentication into app backends and serverless stacks following ai-rules patterns for secure connection strings, roles, and auth-aware queries.
Files
Neon Auth Integration
Add authentication to your application.
When to Use This Skill
- Adding authentication to a new or existing project
- Implementing sign-in, sign-up, and session management
- Configuring social authentication (Google, GitHub)
Package: @neondatabase/auth (auth only, smaller bundle)
Need database queries too? Use the neon-js skill instead for @neondatabase/neon-js with unified auth + data API.
Code Generation Rules
When generating TypeScript/JavaScript code, follow these rules:
Complete reference: See Code Generation Rules for:
- Import path handling (path aliases vs relative imports)
- Neon package imports (subpath exports, adapter patterns)
- CSS import strategy (Tailwind detection, single import method)
- File structure patterns
Key points:
- Check
tsconfig.jsonfor path aliases before generating imports - Use relative imports if unsure or no aliases exist
BetterAuthReactAdapterMUST be imported fromauth/react/adapterssubpath- Adapters are factory functions - call them with
() - Choose ONE CSS import method (Tailwind or CSS, not both)
Available Guides
Each guide is a complete, self-contained walkthrough with numbered phases:
- `guides/nextjs-setup.md` - Complete Next.js App Router setup guide
- `guides/react-spa-setup.md` - Detailed React SPA guide with react-router-dom integration
I'll automatically detect your context (package manager, framework, existing setup) and select the appropriate guide based on your request.
For troubleshooting, see the Troubleshooting Guide in references.
Quick Examples
Tell me what you're building - I'll handle the rest:
- "Add authentication to my Next.js app" -> Loads setup guide, sets up auth routes
- "Set up sign-in with Google" -> Configures social auth provider
- "Debug my auth session not persisting" -> Loads troubleshooting guide
Reference Documentation
Primary Resource: See neon-auth.mdc for comprehensive guidelines including:
- All authentication methods (email/password, social, magic link)
- Session data structure
- UI components reference
- Error handling
Framework-Specific Setup (choose your framework):
Framework-Specific UI (choose your framework):
Shared References:
- Common Mistakes - Import paths, adapter patterns, CSS
- Troubleshooting Guide - Error solutions
- Code Generation Rules - Import and CSS strategies
- Auth Adapters Guide - Adapter comparison
- Import Reference - Complete import paths
Templates
templates/nextjs-api-route.ts- API route handler for Next.jstemplates/auth-client.ts- Client-side auth configuration
Related Skills
- neon-js - Full SDK with auth + database queries (use if you need PostgREST-style data access)
- neon-drizzle - Drizzle ORM setup (for database queries)
- neon-serverless - Direct database connections
- add-neon-docs - Add Neon best practices to your project (run after setup)
---
Workflow
I will: 1. Detect your project context automatically (Next.js, React SPA, Node.js) 2. Select and load the appropriate guide 3. Follow the guide's phases sequentially 4. Track progress using the guide's workflow checklist 5. Load reference files only when needed 6. Offer to add Neon best practices to your project docs
Ready to get started? Just describe what you're building!
Next.js Auth Setup
Complete Walkthrough: This is a self-contained, step-by-step guide with its own numbered phases (Phase 1-8).
Follow each phase in order for a full Neon Auth setup in Next.js App Router.
Complete guide for setting up Neon Auth with Next.js App Router.
Important:
- Remember to run the neon-plugin:add-neon-docs skill with the parameter SKILL_NAME="neon-auth" after completing the guide.
Table of Contents
- Next.js Auth Setup
- Important:
- Table of Contents
- Workflow Checklist
- Phase 1: Context Detection
- Phase 2: Installation
- Phase 3: Environment Configuration
- Phase 4: API Route Setup
- Phase 5: Auth Client Configuration
- Phase 6: UI Provider Setup (Optional)
- 6.1. Import CSS
- 6.2. Create Auth Provider
- 6.3. Wrap App in Provider
- 6.4. Add Navbar with Session Info
- Phase 7: Auth Pages Setup (Optional)
- Phase 8: Validation \& Testing
- 8.1. Manual Testing Checklist
- Phase 9: Add Best Practices References
- Setup Complete!
---
Workflow Checklist
When following this guide, I will track these high-level tasks:
- [ ] Detect project context (package manager, Next.js version, existing auth)
- [ ] Install @neondatabase/auth package
- [ ] Configure environment variables (auth URL)
- [ ] Create API route handler at /api/auth/[...path]
- [ ] Set up auth client for client components
- [ ] (Optional) Set up UI provider with pre-built components
- [ ] (Optional) Create auth pages (/auth/sign-in, etc.)
- [ ] Validate setup and test authentication flow
- [ ] Add Neon Auth best practices to project docs
---
Phase 1: Context Detection
Auto-detect project context:
Check Package Manager:
ls package-lock.json # -> npm
ls bun.lockb # -> bun
ls pnpm-lock.yaml # -> pnpm
ls yarn.lock # -> yarnCheck Next.js Version:
grep '"next"' package.jsonEnsure Next.js 13+ with App Router (pages in app/ directory).
Check Existing Setup:
ls app/api/auth # Auth routes exist?
ls lib/auth # Auth client exists?
grep '@neondatabase' package.json # Already installed?Check for Tailwind:
ls tailwind.config.js tailwind.config.ts 2>/dev/nullCheck Environment Files:
ls .env .env.localPhase 2: Installation
Based on detection, install the auth package:
[package-manager] add @neondatabase/authReplace [package-manager] with your detected package manager (npm install, pnpm add, yarn add, bun add).
Phase 3: Environment Configuration
Outcome: A working .env.local file with the Neon Auth URL.
Create or update .env.local:
# Neon Auth URL - get this from your Neon dashboard
# Format: https://ep-xxx.neonauth.c-2.us-east-2.aws.neon.build/dbname/auth
NEON_AUTH_BASE_URL=your-neon-auth-url
NEXT_PUBLIC_NEON_AUTH_URL=your-neon-auth-urlWhere to find your Auth URL: 1. Go to your Neon project dashboard 2. Navigate to the "Auth" tab 3. Copy the Auth URL
Important: Both variables are needed:
NEON_AUTH_BASE_URL- Used by server-side API routesNEXT_PUBLIC_NEON_AUTH_URL- Used by client-side components (prefixed with NEXT_PUBLIC_)
Add to .gitignore if not already present:
.env.localPhase 4: API Route Setup
Create the API route handler for authentication endpoints:
Create file: app/api/auth/[...path]/route.ts
import { authApiHandler } from "@neondatabase/auth/next";
export const { GET, POST } = authApiHandler();This creates endpoints for:
/api/auth/sign-in- Sign in/api/auth/sign-up- Sign up/api/auth/sign-out- Sign out/api/auth/session- Get session- And other auth-related endpoints
Phase 5: Auth Client Configuration
Create the auth client for use in client components:
Create file: lib/auth/client.ts
import { createAuthClient } from "@neondatabase/auth/next";
export const authClient = createAuthClient();Usage in components:
"use client";
import { authClient } from "@/lib/auth/client";
function AuthStatus() {
const session = authClient.useSession();
if (session.isPending) return <div>Loading...</div>;
if (!session.data) return <SignInButton />;
return (
<div>
<p>Hello, {session.data.user.name}</p>
<button onClick={() => authClient.signOut()}>Sign Out</button>
</div>
);
}
function SignInButton() {
return (
<button onClick={() => authClient.signIn.email({
email: "user@example.com",
password: "password"
})}>
Sign In
</button>
);
}Phase 6: UI Provider Setup (Optional)
Skip this phase if you're building custom auth forms. Use this if you want pre-built UI components.
6.1. Import CSS
Auth UI automatically inherits your app's existing theme. If you have CSS variables like --primary, --background, etc. defined (from Tailwind, shadcn/ui, or custom CSS), auth components use them with no configuration.
Import order doesn't matter - auth styles are in @layer neon-auth, so your styles always win.
If using Tailwind (tailwind.config.{js,ts} exists):
Add to your global CSS file (e.g., app/globals.css):
@import '@neondatabase/auth/ui/tailwind';If NOT using Tailwind:
Add to app/layout.tsx:
import "@neondatabase/auth/ui/css";Warning: Never import both - causes 94KB of duplicate styles.
Auth-specific customization: To customize auth components differently from your main app, use --neon-* prefix variables. See the theming guide for details.
6.2. Create Auth Provider
Create file: app/auth-provider.tsx
"use client";
import { NeonAuthUIProvider } from "@neondatabase/auth/react/ui";
import { authClient } from "@/lib/auth/client";
import { useRouter } from "next/navigation";
import Link from "next/link";
export function AuthProvider({ children }: { children: React.ReactNode }) {
const router = useRouter();
return (
<NeonAuthUIProvider
authClient={authClient}
navigate={router.push}
replace={router.replace}
onSessionChange={() => router.refresh()}
Link={Link}
>
{children}
</NeonAuthUIProvider>
);
}To add social login buttons, add the social prop:
<NeonAuthUIProvider
authClient={authClient}
navigate={router.push}
replace={router.replace}
onSessionChange={() => router.refresh()}
Link={Link}
social={{
// TWO configs required: 1) Enable providers in Neon Console, 2) List them here
providers: ["google", "github"]
}}
>
{children}
</NeonAuthUIProvider>6.3. Wrap App in Provider
Update: app/layout.tsx
import { AuthProvider } from "./auth-provider";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<AuthProvider>{children}</AuthProvider>
</body>
</html>
);
}6.4. Add Navbar with Session Info
Create a navbar component that shows the user's session status:
Create file: components/navbar.tsx
"use client";
import { UserButton, SignedIn, SignedOut } from "@neondatabase/auth/react/ui";
import Link from "next/link";
export function Navbar() {
return (
<nav className="flex items-center justify-between p-4 border-b">
<Link href="/">My App</Link>
<div className="flex items-center gap-4">
<SignedOut>
<Link href="/auth/sign-in">Sign In</Link>
</SignedOut>
<SignedIn>
<UserButton />
</SignedIn>
</div>
</nav>
);
}Add to layout: Update app/layout.tsx to include the navbar:
import { AuthProvider } from "./auth-provider";
import { Navbar } from "@/components/navbar";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<AuthProvider>
<Navbar />
{children}
</AuthProvider>
</body>
</html>
);
}Components explained:
<SignedOut>- Only renders children when user is NOT authenticated<SignedIn>- Only renders children when user IS authenticated<UserButton />- Displays user avatar with dropdown menu (sign out, account settings)
Phase 7: Auth Pages Setup (Optional)
Skip this phase if you're using custom auth forms. Use this for pre-built auth pages.
Create file: app/auth/[path]/page.tsx
import { AuthView } from "@neondatabase/auth/react/ui";
import { authViewPaths } from "@neondatabase/auth/react/ui/server";
export const dynamicParams = false;
export function generateStaticParams() {
return Object.values(authViewPaths).map((path) => ({ path }));
}
export default async function AuthPage({
params,
}: {
params: Promise<{ path: string }>;
}) {
const { path } = await params;
return <AuthView pathname={path} />;
}This creates routes for:
/auth/sign-in- Sign in page/auth/sign-up- Sign up page/auth/forgot-password- Password reset request/auth/reset-password- Password reset form/auth/magic-link- Magic link sign in/auth/two-factor- Two-factor authentication/auth/callback- OAuth callback/auth/sign-out- Sign out page
Phase 8: Validation & Testing
8.1. Manual Testing Checklist
- [ ] Start development server:
npm run dev - [ ] Navigate to
/auth/sign-up(if using pre-built pages) - [ ] Create a test account
- [ ] Sign out
- [ ] Sign back in
- [ ] Verify session persists across page refresh
- [ ] Check browser console for errors
Common Issues:
- "Module not found" - Check import paths match subpath exports
- Session not persisting - Verify API route is correctly configured
- CSS not loading - Check you imported CSS in layout (only one method)
For detailed error resolution, see:
Phase 9: Add Best Practices References
Before executing the add-neon-docs skill, provide a summary of everything that has been done:
"Neon Auth integration is complete! Now adding documentation references..."
Then execute the neon-plugin:add-neon-docs skill with the parameter SKILL_NAME="neon-auth"
This will add reference links to Neon Auth best practices documentation in your project's AI documentation file.
---
Setup Complete!
Your Neon Auth integration is ready to use.
What's working:
- Authentication API routes at
/api/auth/* - Client-side auth hooks via
authClient.useSession() - (If configured) Pre-built UI components and auth pages
Next steps:
- Add protected routes using session checks
- Customize UI theme (see neon-auth.mdc for theming)
- Set up social OAuth providers in Neon dashboard
React SPA Auth Setup
Complete guide for setting up Neon Auth with React SPAs (Vite, Create React App) using react-router-dom.
Table of Contents
- React SPA Auth Setup
- Table of Contents
- Phase 1: Auth Client
- Phase 2: UI Setup (Optional)
- 2a. Install react-router-dom
- 2b. Import CSS
- 2c. CSS Variables Reference
- 2d. Update main.tsx with BrowserRouter
- 2e. Create Auth Provider
- 2f. Add Routes to App.tsx
- Phase 3: Account Settings (Optional)
- Add account routes to App.tsx
- Phase 4: Validation
- Complete App.tsx Example
---
Phase 1: Auth Client
Create src/lib/auth-client.ts:
For `@neondatabase/auth`:
import { createAuthClient } from "@neondatabase/auth";
import { BetterAuthReactAdapter } from "@neondatabase/auth/react/adapters";
export const authClient = createAuthClient(
import.meta.env.VITE_NEON_AUTH_URL,
{ adapter: BetterAuthReactAdapter() }
);For `@neondatabase/neon-js`:
import { createClient } from "@neondatabase/neon-js";
import { BetterAuthReactAdapter } from "@neondatabase/neon-js/auth/react/adapters";
export const client = createClient({
auth: {
adapter: BetterAuthReactAdapter(),
url: import.meta.env.VITE_NEON_AUTH_URL,
},
dataApi: {
url: import.meta.env.VITE_NEON_DATA_API_URL,
},
});
// For convenience, export auth separately
export const authClient = client.auth;Critical:
BetterAuthReactAdaptermust be imported from the/react/adapterssubpath- The adapter must be called as a function:
BetterAuthReactAdapter()
---
Phase 2: UI Setup (Optional)
Ask: "Want to add pre-built auth UI components? (sign-in, sign-up forms, user button, account settings)"
If yes, continue with sub-steps below.
2a. Install react-router-dom
npm install react-router-domUI components are included in the main package, you only need react-router-dom for navigation.
2b. Import CSS
Auth UI automatically inherits your app's existing theme. If you have CSS variables like --primary, --background, etc. defined (from Tailwind, shadcn/ui, or custom CSS), auth components use them with no configuration.
Import order doesn't matter - auth styles are in @layer neon-auth, so your styles always win.
Choose ONE import method. Never import both - it causes duplicate styles.
If NOT using Tailwind - Add to src/main.tsx or entry point:
For @neondatabase/auth:
import '@neondatabase/auth/ui/css';For @neondatabase/neon-js:
import '@neondatabase/neon-js/ui/css';If using Tailwind CSS v4 - Add to main CSS file (e.g., index.css):
For @neondatabase/auth:
@import 'tailwindcss';
@import '@neondatabase/auth/ui/tailwind';For @neondatabase/neon-js:
@import 'tailwindcss';
@import '@neondatabase/neon-js/ui/tailwind';2c. CSS Variables Reference
Auth UI automatically inherits these variables if you have them defined. Use them in custom components for consistency:
| Variable | Purpose |
|---|---|
--background, --foreground | Page background/text |
--card, --card-foreground | Card surfaces |
--primary, --primary-foreground | Primary buttons/actions |
--muted, --muted-foreground | Muted/subtle elements |
--border, --ring | Borders and focus rings |
--radius | Border radius |
Auth-specific customization: To customize auth components differently from your main app, use --neon-* prefix:
:root {
--primary: oklch(0.55 0.25 250); /* Your app's blue */
--neon-primary: oklch(0.55 0.18 145); /* Auth uses green */
}Example - Custom Navbar Styling:
/* ✅ Correct - uses CSS variables, supports dark mode automatically */
.navbar {
background: var(--background);
border-bottom: 1px solid var(--border);
color: var(--foreground);
}
/* ❌ Wrong - hardcoded colors won't match theme or support dark mode */
.navbar {
background: #fff;
border-bottom: 1px solid #e5e5e5;
color: #111;
}Dark mode: Add the dark class to <html> or <body>. All CSS variable values automatically adjust.
Complete theming guide: See UI Theming Guide
2d. Update main.tsx with BrowserRouter
For @neondatabase/auth:
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import '@neondatabase/auth/ui/css'; // if not using Tailwind
import App from './App';
import { Providers } from './providers';
createRoot(document.getElementById('root')!).render(
<BrowserRouter>
<Providers>
<App />
</Providers>
</BrowserRouter>
);For @neondatabase/neon-js:
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import '@neondatabase/neon-js/ui/css'; // if not using Tailwind
import App from './App';
import { Providers } from './providers';
createRoot(document.getElementById('root')!).render(
<BrowserRouter>
<Providers>
<App />
</Providers>
</BrowserRouter>
);2e. Create Auth Provider
Create src/providers.tsx:
For @neondatabase/auth:
import { NeonAuthUIProvider } from '@neondatabase/auth/react/ui';
import { useNavigate, Link as RouterLink } from 'react-router-dom';
import { authClient } from './lib/auth-client';
import type { ReactNode } from 'react';
// Adapter for react-router-dom Link
function Link({ href, ...props }: { href: string } & React.AnchorHTMLAttributes<HTMLAnchorElement>) {
return <RouterLink to={href} {...props} />;
}
export function Providers({ children }: { children: ReactNode }) {
const navigate = useNavigate();
return (
<NeonAuthUIProvider
authClient={authClient}
navigate={(path) => navigate(path)}
replace={(path) => navigate(path, { replace: true })}
onSessionChange={() => {
// Optional: refresh data or invalidate cache
}}
Link={Link}
social={{
// TWO configs required: 1) Enable providers in Neon Console, 2) List them here
providers: ['google', 'github']
}}
>
{children}
</NeonAuthUIProvider>
);
}For @neondatabase/neon-js:
import { NeonAuthUIProvider } from '@neondatabase/neon-js/auth/react/ui';
import { useNavigate, Link as RouterLink } from 'react-router-dom';
import { authClient } from './lib/auth-client';
import type { ReactNode } from 'react';
// Adapter for react-router-dom Link
function Link({ href, ...props }: { href: string } & React.AnchorHTMLAttributes<HTMLAnchorElement>) {
return <RouterLink to={href} {...props} />;
}
export function Providers({ children }: { children: ReactNode }) {
const navigate = useNavigate();
return (
<NeonAuthUIProvider
authClient={authClient}
navigate={(path) => navigate(path)}
replace={(path) => navigate(path, { replace: true })}
onSessionChange={() => {
// Optional: refresh data or invalidate cache
}}
Link={Link}
social={{
// TWO configs required: 1) Enable providers in Neon Console, 2) List them here
providers: ['google', 'github']
}}
>
{children}
</NeonAuthUIProvider>
);
}Provider props explained:
navigate: Function to navigate to a new routereplace: Function to replace current route (for redirects)onSessionChange: Callback when auth state changes (useful for cache invalidation)Link: Adapter component for react-router-dom's Linksocial: Display social login buttons. Requires TWO configurations: enable in Console + add this prop
2f. Add Routes to App.tsx
For @neondatabase/auth:
import { Routes, Route, useParams } from 'react-router-dom';
import { AuthView, UserButton, SignedIn, SignedOut } from '@neondatabase/auth/react/ui';
// Auth page - handles /auth/sign-in, /auth/sign-up, etc.
function AuthPage() {
const { pathname } = useParams();
return (
<div className="flex min-h-screen items-center justify-center">
<AuthView pathname={pathname} />
</div>
);
}
// Simple navbar example
function Navbar() {
return (
<nav className="flex items-center justify-between p-4 border-b">
<a href="/">My App</a>
<div className="flex items-center gap-4">
<SignedOut>
<a href="/auth/sign-in">Sign In</a>
</SignedOut>
<SignedIn>
<UserButton />
</SignedIn>
</div>
</nav>
);
}
function HomePage() {
return <div>Welcome to My App!</div>;
}
export default function App() {
return (
<>
<Navbar />
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/auth/:pathname" element={<AuthPage />} />
</Routes>
</>
);
}For @neondatabase/neon-js:
import { Routes, Route, useParams } from 'react-router-dom';
import { AuthView, UserButton, SignedIn, SignedOut } from '@neondatabase/neon-js/auth/react/ui';
// Auth page - handles /auth/sign-in, /auth/sign-up, etc.
function AuthPage() {
const { pathname } = useParams();
return (
<div className="flex min-h-screen items-center justify-center">
<AuthView pathname={pathname} />
</div>
);
}
// Simple navbar example
function Navbar() {
return (
<nav className="flex items-center justify-between p-4 border-b">
<a href="/">My App</a>
<div className="flex items-center gap-4">
<SignedOut>
<a href="/auth/sign-in">Sign In</a>
</SignedOut>
<SignedIn>
<UserButton />
</SignedIn>
</div>
</nav>
);
}
function HomePage() {
return <div>Welcome to My App!</div>;
}
export default function App() {
return (
<>
<Navbar />
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/auth/:pathname" element={<AuthPage />} />
</Routes>
</>
);
}Auth routes created:
/auth/sign-in- Sign in page/auth/sign-up- Sign up page/auth/forgot-password- Password reset request/auth/reset-password- Set new password/auth/sign-out- Sign out/auth/callback- OAuth callback (internal)
---
Phase 3: Account Settings (Optional)
Ask: "Want to add account settings pages where users can manage their profile?"
If yes:
Add account routes to App.tsx
For @neondatabase/auth:
import { AccountView } from '@neondatabase/auth/react/ui';
// Account settings page
function AccountPage() {
const { pathname } = useParams();
return (
<div className="container mx-auto py-8">
<AccountView pathname={pathname} />
</div>
);
}
// Add to your Routes
<Route path="/account/:pathname" element={<AccountPage />} />For @neondatabase/neon-js:
import { AccountView } from '@neondatabase/neon-js/auth/react/ui';
// Account settings page
function AccountPage() {
const { pathname } = useParams();
return (
<div className="container mx-auto py-8">
<AccountView pathname={pathname} />
</div>
);
}
// Add to your Routes
<Route path="/account/:pathname" element={<AccountPage />} />Account routes created:
/account/settings- Profile settings (name, avatar, email)/account/security- Password, sessions, 2FA/account/sessions- Active sessions management
---
Phase 4: Validation
After setup completes, guide user through testing:
- [ ] Start development server:
npm run dev - [ ] Navigate to
/auth/sign-up - [ ] Create a test account
- [ ] Sign out
- [ ] Sign back in
- [ ] Verify session persists across page refresh
- [ ] Check browser console for errors
Common Issues:
- "Module not found" - Check import paths match subpath exports
- Session not persisting - Verify auth client is configured correctly
- CSS not loading - Check you imported CSS (only one method)
---
Complete App.tsx Example
Here's a complete example with all routes:
import { Routes, Route, useParams } from 'react-router-dom';
import {
AuthView,
AccountView,
UserButton,
SignedIn,
SignedOut
} from '@neondatabase/auth/react/ui';
function AuthPage() {
const { pathname } = useParams();
return (
<div className="flex min-h-screen items-center justify-center">
<AuthView pathname={pathname} />
</div>
);
}
function AccountPage() {
const { pathname } = useParams();
return (
<div className="container mx-auto py-8">
<AccountView pathname={pathname} />
</div>
);
}
function Navbar() {
return (
<nav className="flex items-center justify-between p-4 border-b">
<a href="/">My App</a>
<div className="flex items-center gap-4">
<SignedOut>
<a href="/auth/sign-in">Sign In</a>
</SignedOut>
<SignedIn>
<UserButton />
</SignedIn>
</div>
</nav>
);
}
function HomePage() {
return (
<div className="container mx-auto py-8">
<h1>Welcome to My App!</h1>
<SignedIn>
<p>You are signed in.</p>
</SignedIn>
<SignedOut>
<p>Please sign in to continue.</p>
</SignedOut>
</div>
);
}
export default function App() {
return (
<>
<Navbar />
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/auth/:pathname" element={<AuthPage />} />
<Route path="/account/:pathname" element={<AccountPage />} />
</Routes>
</>
);
}---
Guide Version: 1.0.0 Last Updated: 2025-12-09
/**
* Neon Auth Client Configuration
*
* Place this file at: lib/auth/client.ts (or your preferred location)
*
* Usage in components:
* import { authClient } from "@/lib/auth/client";
* const session = authClient.useSession();
*/
import { createAuthClient } from '@neondatabase/auth/next';
/**
* Auth client for use in client components.
* Automatically uses environment variables:
* - NEXT_PUBLIC_NEON_AUTH_URL
*/
export const authClient = createAuthClient();
/**
* Example usage in a component:
*
* "use client";
* import { authClient } from "@/lib/auth/client";
*
* function AuthStatus() {
* const session = authClient.useSession();
*
* if (session.isPending) return <div>Loading...</div>;
* if (!session.data) return <button onClick={() => authClient.signIn.email({ email, password })}>Sign In</button>;
*
* return (
* <div>
* <p>Hello, {session.data.user.name}</p>
* <button onClick={() => authClient.signOut()}>Sign Out</button>
* </div>
* );
* }
*/
/**
* Neon Auth API Route Handler for Next.js
*
* Place this file at: app/api/auth/[...path]/route.ts
*
* This creates all necessary authentication endpoints:
* - /api/auth/sign-in
* - /api/auth/sign-up
* - /api/auth/sign-out
* - /api/auth/session
* - /api/auth/callback/* (for OAuth)
*/
import { authApiHandler } from "@neondatabase/auth/next";
export const { GET, POST } = authApiHandler();