### Build and Run Example Applications
Source: https://github.com/neondatabase/neon-js/blob/main/CLAUDE.md
Navigate to an example directory, install dependencies, and start the development server or build for production.
```bash
cd examples/react-neon-js # or nextjs-neon-auth, react-auth-external-ui
pnpm install
pnpm run dev # Development server
pnpm run build # Production build
```
--------------------------------
### Run Development Server
Source: https://github.com/neondatabase/neon-js/blob/main/examples/neon-auth-magic-link-example/README.md
Navigate to the example's directory and start the development server using Bun.
```bash
cd examples/neon-auth-magic-link-example
bun run dev
```
--------------------------------
### Copy Environment Variables
Source: https://github.com/neondatabase/neon-js/blob/main/examples/nextjs-phone-login/README.md
Copy the example environment variables file to start configuring your application. This sets up the necessary variables for Neon Auth and database connection.
```bash
cp .env.example .env
```
--------------------------------
### Install Neon.js SDK
Source: https://github.com/neondatabase/neon-js/blob/main/packages/neon-js/README.md
Install the Neon.js SDK using npm or bun.
```bash
npm install @neondatabase/neon-js
# or
bun add @neondatabase/neon-js
```
--------------------------------
### Build Packages and Example App
Source: https://github.com/neondatabase/neon-js/blob/main/AGENTS.md
Build the Neon.js packages and the example React application. This is a prerequisite for running E2E tests locally.
```bash
pnpm run build
cd examples/react-neon-js && pnpm run build
```
--------------------------------
### Install Dependencies
Source: https://github.com/neondatabase/neon-js/blob/main/DEVELOPMENT.md
Run this command to install all necessary project dependencies using pnpm.
```bash
pnpm install
```
--------------------------------
### Install @neondatabase/auth-ui
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth-ui/README.md
Install the auth-ui package using npm or bun.
```bash
npm install @neondatabase/auth-ui
# or
bun add @neondatabase/auth-ui
```
--------------------------------
### Install @neondatabase/auth
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth/README.md
Install the authentication package using npm or bun.
```bash
npm install @neondatabase/auth
# or
bun add @neondatabase/auth
```
--------------------------------
### Install @neondatabase/auth
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth/llms.txt
Install the authentication package using npm.
```bash
npm install @neondatabase/auth
```
--------------------------------
### Start Development Server
Source: https://github.com/neondatabase/neon-js/blob/main/examples/nextjs-phone-login/README.md
Start the Next.js development server. This command launches the application locally, allowing you to test the authentication flows.
```bash
bun dev
```
--------------------------------
### Install Postgrest JS Client
Source: https://github.com/neondatabase/neon-js/blob/main/packages/postgrest-js/README.md
Install the @neondatabase/postgrest-js package using npm or bun.
```bash
npm install @neondatabase/postgrest-js
# or
bun add @neondatabase/postgrest-js
```
--------------------------------
### Full NeonAuthUIProvider Configuration
Source: https://github.com/neondatabase/neon-js/blob/main/skills/neon-auth-nextjs/SKILL.md
Example of a comprehensive NeonAuthUIProvider setup with all available props for authentication, navigation, social providers, feature flags, and customization.
```typescript
router.refresh()} // Refresh Server Components!
redirectTo="/dashboard" // Where to redirect after auth
Link={({href, children}) => {children}} // Next.js Link component
// Social/OAuth Providers
social={{
providers: ['google'],
}}
// Feature Flags
emailOTP={true} // Enable email OTP sign-in
emailVerification={true} // Require email verification
magicLink={false} // Magic link (disabled by default)
multiSession={false} // Multiple sessions (disabled)
// Credentials Configuration
credentials={{
forgotPassword: true, // Show forgot password link
}}
// Sign Up Fields
signUp={{
fields: ['name'], // Additional fields: 'name', 'username', etc.
}}
// Account Settings Fields
account={{
fields: ['image', 'name', 'company', 'age', 'newsletter'],
}}
// Organization Features
organization={{}
// Dark Mode
defaultTheme="system" // 'light' | 'dark' | 'system'
// Custom Labels
localization={{
SIGN_IN: 'Welcome Back',
SIGN_UP: 'Create Account',
FORGOT_PASSWORD: 'Forgot Password?',
OR_CONTINUE_WITH: 'or continue with',
}}
>
{children}
```
--------------------------------
### Install @neondatabase/auth-ui
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth-ui/llms.txt
Install the auth-ui package along with the core auth package using npm.
```bash
npm install @neondatabase/auth-ui @neondatabase/auth
```
--------------------------------
### Install Dependencies and Run Dev Server
Source: https://github.com/neondatabase/neon-js/blob/main/examples/nextjs-admin-portal/README.md
Install project dependencies from the monorepo root and run the Next.js development server for the admin portal. Ensure your environment variables are set up.
```bash
bun install
cd examples/nextjs-admin-portal
cp .env.example .env
# Edit .env with your Neon Auth credentials
bun dev
```
--------------------------------
### Install Dependencies with Bun
Source: https://github.com/neondatabase/neon-js/blob/main/examples/nextjs-neon-auth/README.md
Installs project dependencies using the Bun package manager. Ensure Bun is installed before running.
```bash
bun install
```
--------------------------------
### Copy Environment File
Source: https://github.com/neondatabase/neon-js/blob/main/examples/neon-auth-magic-link-example/README.md
Copy the example environment file to a local configuration file. Remember to fill in your specific values.
```bash
cp .env.example .env.local
```
--------------------------------
### Install UI Package
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth/README.md
Installs the UI package alongside the main auth package. This is a prerequisite for using the pre-built UI components.
```bash
npm install @neondatabase/auth-ui
```
--------------------------------
### Create and Edit Environment File
Source: https://github.com/neondatabase/neon-js/blob/main/examples/cross-domain-cookies/DOCKER-QUICKSTART.md
Copy the example environment file and edit it with your Neon Auth credentials and database connection details.
```bash
# Copy the example
cp .env.docker.example .env
# Edit with your credentials
nano .env
```
--------------------------------
### Authentication Layer Tests Setup
Source: https://github.com/neondatabase/neon-js/blob/main/CLAUDE.md
Describes the testing setup for the authentication layer, utilizing real SDKs with MSW for network mocking and providing instructions for running tests.
```typescript
src/__tests__/
- Uses real Better Auth SDK with MSW for network mocking
- Run with pnpm test:node for reliable MSW interception
```
--------------------------------
### Build and Start Docker Services
Source: https://github.com/neondatabase/neon-js/blob/main/examples/cross-domain-cookies/DOCKER-TESTING.md
Builds the Docker images and starts all defined services using Docker Compose. Use the -d flag to run in detached mode.
```bash
# Build and start all services
docker-compose up --build
# Or run in background
docker-compose up -d --build
```
--------------------------------
### Run Development Server
Source: https://github.com/neondatabase/neon-js/blob/main/examples/nextjs-neon-auth/README.md
Starts the Next.js development server using Bun. Access the application at http://localhost:3000.
```bash
bun run dev
```
--------------------------------
### Set Up Environment Variables
Source: https://github.com/neondatabase/neon-js/blob/main/examples/nextjs-neon-auth/README.md
Copies the example environment file and prompts to edit it with Neon Auth URL and Cookie secret. This is crucial for the application's authentication to function correctly.
```bash
cd examples/nextjs
cp .env.example .env
# Edit .env with your Neon Auth URL and Cookie secret
```
--------------------------------
### Install Neon.js for React Auth UI
Source: https://github.com/neondatabase/neon-js/blob/main/examples/react-auth-external-ui/README.md
Install the Neon.js package using npm to use its authentication UI components.
```bash
npm install @neondatabase/neon-js
```
--------------------------------
### NeonPostgrestClient Constructor Options Example
Source: https://github.com/neondatabase/neon-js/blob/main/packages/postgrest-js/README.md
Demonstrates initializing NeonPostgrestClient with specific schema and custom global headers.
```typescript
const client = new NeonPostgrestClient({
dataApiUrl: 'https://your-api-url.com/rest/v1',
options: {
db: { schema: 'public' },
global: {
headers: { 'X-Custom-Header': 'value' },
},
},
});
```
--------------------------------
### Install Neon Auth Packages
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth/NEXT-JS.md
Install the necessary Neon Auth packages for your Next.js project using npm, pnpm, or yarn.
```bash
npm install @neondatabase/auth @neondatabase/auth-ui
# or
pnpm add @neondatabase/auth @neondatabase/auth-ui
# or
yarn add @neondatabase/auth @neondatabase/auth-ui
```
--------------------------------
### Copy Docker Environment File
Source: https://github.com/neondatabase/neon-js/blob/main/examples/cross-domain-cookies/DOCKER-TESTING.md
Copies the example Docker environment file to be used for configuration.
```bash
cp .env.docker.example .env
```
--------------------------------
### Setup NeonAuthUIProvider
Source: https://github.com/neondatabase/neon-js/blob/main/packages/neon-js/README.md
Configures the `NeonAuthUIProvider` with an authentication client and a redirect URL for authentication flows.
```typescript
"use client"
import { NeonAuthUIProvider } from "@neondatabase/auth-ui"
import "@neondatabase/auth-ui/css"
export function Providers({ children }) {
return (
{children}
)
}
```
--------------------------------
### Quick Start with Neon.js Client
Source: https://github.com/neondatabase/neon-js/blob/main/packages/neon-js/llms.txt
Initialize the Neon.js client, authenticate a user, and perform a database query. The token is automatically injected for queries.
```typescript
import { createClient } from '@neondatabase/neon-js';
const client = createClient({
auth: {
url: import.meta.env.VITE_NEON_AUTH_URL,
},
dataApi: {
url: import.meta.env.VITE_NEON_DATA_API_URL,
},
});
// Authenticate
await client.auth.signIn.email({
email: 'user@example.com',
password: 'secure-password',
});
// Query database (token automatically injected)
const { data: users } = await client
.from('users')
.select('*')
.eq('status', 'active');
```
--------------------------------
### Production Cookie Configuration Example
Source: https://github.com/neondatabase/neon-js/blob/main/examples/cross-domain-cookies/DOCKER-TESTING.md
Example of configuring Neon Auth for production with a custom domain and secure cookie attributes.
```typescript
export const auth = createNeonAuth({
baseUrl: process.env.NEON_AUTH_BASE_URL!,
cookies: {
secret: process.env.NEON_AUTH_COOKIE_SECRET!,
domain: '.example.com', // Shares across app.example.com, admin.example.com
sessionDataTtl: 300,
},
});
```
--------------------------------
### Quick Start: Initialize Client and Query Database
Source: https://github.com/neondatabase/neon-js/blob/main/packages/neon-js/README.md
Initialize the Neon.js client with authentication and Data API URLs, then authenticate a user and query the database. Ensure your Database type is generated.
```typescript
import { createClient } from '@neondatabase/neon-js';
// Database type generated via: npx @neondatabase/neon-js gen-types --db-url "..."
// See "TypeScript" section below for details
const client = createClient({
auth: {
url: import.meta.env.VITE_NEON_AUTH_URL,
// Optional: allow unauthenticated users to query data via RLS
// allowAnonymous: true,
},
dataApi: {
url: import.meta.env.VITE_NEON_DATA_API_URL,
},
});
// Authenticate
await client.auth.signIn.email({
email: 'user@example.com',
password: 'secure-password',
});
// Query database (token automatically injected)
const { data: users } = await client
.from('users')
.select('*')
.eq('status', 'active');
```
--------------------------------
### Install next-themes for Next.js Theming
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth-ui/llms.txt
Installs the next-themes package, which is recommended for managing themes in Next.js applications. This enables easy switching between light, dark, and system themes.
```bash
npm install next-themes
```
--------------------------------
### Run E2E Tests
Source: https://github.com/neondatabase/neon-js/blob/main/CLAUDE.md
Commands to build packages and the example app, then run end-to-end tests locally. Requires Neon Auth/Data API credentials.
```bash
# Build packages and example app first
pnpm run build
cd examples/react-neon-js && pnpm run build
# Run E2E tests
pnpm run --filter e2e test:ci
```
--------------------------------
### fetchWithToken Usage Example
Source: https://github.com/neondatabase/neon-js/blob/main/packages/postgrest-js/README.md
Shows how to create a wrapped fetch function using fetchWithToken and then use it to initialize the NeonPostgrestClient.
```typescript
const authFetch = fetchWithToken(async () => {
return await getTokenFromYourAuthSystem();
});
// Use with client
const client = new NeonPostgrestClient({
dataApiUrl: 'https://api.example.com',
options: { global: { fetch: authFetch } },
});
```
--------------------------------
### Install Neon Auth and Serverless Dependencies
Source: https://github.com/neondatabase/neon-js/blob/main/examples/neon-auth-orgs-example/README.md
Add the necessary Neon Auth and serverless driver packages to your project. These are required for authentication and database access.
```bash
bun add @neondatabase/auth @neondatabase/serverless
```
--------------------------------
### Next.js Client-Side Setup
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth/llms.txt
Initializes the Neon authentication client for client-side usage within a Next.js application.
```typescript
// lib/auth/client.ts - Client-side
"use client"
import { createAuthClient } from '@neondatabase/auth/next';
export const authClient = createAuthClient();
```
--------------------------------
### Install Dependencies for better-auth-ui
Source: https://github.com/neondatabase/neon-js/blob/main/examples/react-auth-external-ui/README.md
Installs core Neon.js auth packages, better-auth-ui, React Router, and their peer dependencies. Also includes Tailwind CSS and development dependencies.
```bash
# Core packages
npm install @neondatabase/neon-js @daveyplate/better-auth-ui react-router-dom
# Peer dependencies for better-auth-ui
npm install @radix-ui/react-avatar @radix-ui/react-checkbox @radix-ui/react-dialog \
@radix-ui/react-dropdown-menu @radix-ui/react-label @radix-ui/react-select \
@radix-ui/react-separator @radix-ui/react-slot @radix-ui/react-tabs \
@radix-ui/react-tooltip @hookform/resolvers class-variance-authority clsx \
input-otp lucide-react next-themes react-hook-form sonner tailwind-merge zod
# Tailwind CSS v4
npm install tailwindcss @tailwindcss/vite
# Dev dependencies
npm install -D tw-animate-css
```
--------------------------------
### Run in Watch Mode
Source: https://github.com/neondatabase/neon-js/blob/main/README.md
Starts all packages in watch mode for continuous development.
```bash
pnpm dev
```
--------------------------------
### Anonymous Access Example
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth/README.md
Example demonstrating how to enable anonymous data access by setting `allowAnonymous` to `true` in the auth client configuration.
```APIDOC
## Anonymous Access
### Description
Enable `allowAnonymous` to let unauthenticated users access data via RLS policies.
### Example
```typescript
import { createAuthClient } from '@neondatabase/auth';
const auth = createAuthClient('https://your-auth-server.com', {
allowAnonymous: true, // Enable anonymous data access
});
// Get token - returns anonymous token if no user session exists
const token = await auth.getJWTToken?.();
```
This is useful when you want to allow read-only public access to certain data while still enforcing RLS policies.
```
--------------------------------
### OKLCH Color Format Examples
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth-ui/llms.txt
Demonstrates the OKLCH color format used by Neon Auth UI, including examples with and without alpha transparency. Use OKLCH for perceptually uniform colors.
```css
--primary: oklch(0.55 0.25 250); /* Vivid blue */
--primary: oklch(0.55 0.25 250 / 50%); /* 50% opacity */
--muted: oklch(0.5 0 0); /* Neutral gray (no chroma) */
```
--------------------------------
### Next.js Integration - Client Setup
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth/llms.txt
Configuration for setting up Neon Auth on the client-side in a Next.js application.
```APIDOC
## Next.js Client Integration
### Description
This section details how to set up the Neon Auth client for client-side usage in a Next.js application.
### Client-side Setup (`lib/auth/client.ts`)
```typescript
"use client"
import { createAuthClient } from '@neondatabase/auth/next';
export const authClient = createAuthClient();
```
### Server Components
Server components using `auth` methods must be rendered dynamically.
```typescript
import { auth } from '@/lib/auth/server';
export const dynamic = 'force-dynamic';
const { data: session } = await auth.getSession();
```
### Server Actions
Authentication methods can be directly used within Server Actions.
```typescript
import { auth } from '@/lib/auth/server';
await auth.signIn.email({ email, password });
```
```
--------------------------------
### Next.js Integration - Server Setup
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth/llms.txt
Configuration for setting up Neon Auth on the server-side in a Next.js application.
```APIDOC
## Next.js Server Integration
### Description
This section outlines how to set up Neon Auth for server-side functionality in a Next.js application, including environment variables and the unified server entry point.
### Environment Variables
* `NEON_AUTH_BASE_URL`: The base URL for the Neon authentication service.
* `NEON_AUTH_COOKIE_SECRET`: A secret key (at least 32 characters long) for cookie encryption.
### Unified Server Setup (`lib/auth/server.ts`)
```typescript
import { createNeonAuth } from '@neondatabase/auth/next/server';
export const auth = createNeonAuth({
baseUrl: process.env.NEON_AUTH_BASE_URL!,
cookies: {
secret: process.env.NEON_AUTH_COOKIE_SECRET!,
sessionDataTtl: 300, // Optional: session data cache TTL in seconds (default: 5 min)
domain: '.example.com', // Optional: for cross-subdomain cookies
},
});
```
### API Handler (`app/api/auth/[...path]/route.ts`)
```typescript
import { auth } from '@/lib/auth/server';
export const { GET, POST } = auth.handler();
```
### Middleware (`middleware.ts`)
```typescript
import { auth } from '@/lib/auth/server';
export default auth.middleware({ loginUrl: '/auth/sign-in' });
```
```
--------------------------------
### NeonAuthUIProvider Setup
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth-ui/README.md
Configure the NeonAuthUIProvider with your auth client, navigation functions, and desired authentication options like email OTP and social providers.
```typescript
"use client"
import { NeonAuthUIProvider } from "@neondatabase/auth-ui"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { authClient } from "@/lib/auth-client"
export function Providers({ children }: { children: React.ReactNode }) {
const router = useRouter()
return (
router.refresh()}
emailOTP
social={{ providers: ["google"] }}
redirectTo="/dashboard"
Link={Link}
organization={{}}
>
{children}
)
}
```
--------------------------------
### Setup NeonAuthUIProvider
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth/README.md
Configures the `NeonAuthUIProvider` with the auth client and a redirect destination. This component should wrap your application to enable UI-based authentication flows.
```typescript
"use client"
import { NeonAuthUIProvider } from "@neondatabase/auth-ui"
import { createAuthClient } from "@neondatabase/auth"
import "@neondatabase/auth-ui/css"
const authClient = createAuthClient('https://your-auth-url.com')
export function AuthProvider({ children }) {
return (
{children}
)
}
```
--------------------------------
### Build and Run Docker Compose
Source: https://github.com/neondatabase/neon-js/blob/main/examples/cross-domain-cookies/DOCKER-QUICKSTART.md
Build the Docker images and start the services defined in docker-compose.yml. Use the '-d' flag to run in detached mode.
```bash
docker-compose up --build
```
```bash
docker-compose up -d --build
```
--------------------------------
### Next.js Server Setup with Neon Auth
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth/llms.txt
Configures the Neon authentication client for server-side use in a Next.js application, including environment variable setup for base URL and cookie secrets, and defines API handlers and middleware for route protection.
```bash
NEON_AUTH_BASE_URL=https://your-project.neon.tech
NEON_AUTH_COOKIE_SECRET=your-secret-at-least-32-characters-long
```
```typescript
// lib/auth/server.ts - Single entry point for all server functionality
import { createNeonAuth } from '@neondatabase/auth/next/server';
export const auth = createNeonAuth({
baseUrl: process.env.NEON_AUTH_BASE_URL!,
cookies: {
secret: process.env.NEON_AUTH_COOKIE_SECRET!,
sessionDataTtl: 300,
domain: '.example.com',
},
});
```
```typescript
// app/api/auth/[...path]/route.ts - API handler
import { auth } from '@/lib/auth/server';
export const { GET, POST } = auth.handler();
```
```typescript
// middleware.ts - Route protection
import { auth } from '@/lib/auth/server';
export default auth.middleware({ loginUrl: '/auth/sign-in' });
```
--------------------------------
### Protected Route Setup
Source: https://github.com/neondatabase/neon-js/blob/main/skills/neon-js-react/SKILL.md
Demonstrates how to set up protected routes in a React application using `react-router-dom` and Neon.js authentication components like `ProtectedRoute`, `AuthLoading`, `RedirectToSignIn`, and `SignedIn`.
```typescript
// routes.tsx
import { Routes, Route } from 'react-router-dom';
export function AppRoutes() {
return (
{/* Public */}
} />
{/* Auth */}
} />
{/* Protected */}
} />
} />
);
}
// ProtectedRoute.tsx
function ProtectedRoute({ children }: { children: React.ReactNode }) {
return (
<>
{children}
>
);
}
```
--------------------------------
### Consumer CSS Layering Example
Source: https://github.com/neondatabase/neon-js/blob/main/dev-notes/solutions/ui-bugs/css-variables-theme-conflict.md
Shows how library consumers can use CSS layers to guarantee their own styles have higher priority than library styles.
```css
@layer vendor, app;
@import '@neondatabase/auth-ui/css' layer(vendor);
/* Your styles go in 'app' layer or unlayered (highest priority) */
```
--------------------------------
### Environment Variables for Neon.js
Source: https://github.com/neondatabase/neon-js/blob/main/packages/neon-js/llms.txt
Configure environment variables for Neon Auth and Data API URLs, with examples for React/Vite and Next.js.
```bash
# React/Vite
VITE_NEON_AUTH_URL=https://your-project.neon.tech/auth
VITE_NEON_DATA_API_URL=https://your-project.neon.tech/rest/v1
# Next.js
NEON_AUTH_BASE_URL=https://your-project.neon.tech
```
--------------------------------
### Postgrest-JS Querying Examples
Source: https://github.com/neondatabase/neon-js/blob/main/packages/postgrest-js/README.md
Demonstrates common database operations including SELECT, INSERT, UPDATE, DELETE, and calling stored procedures (RPC) using the Postgrest-JS client.
```typescript
const { data } = await client
.from('users')
.select('id, name, email')
.eq('status', 'active')
.order('created_at', { ascending: false })
.limit(10);
```
```typescript
const { data } = await client
.from('users')
.insert({ name: 'Alice', email: 'alice@example.com' })
.select();
```
```typescript
const { data } = await client
.from('users')
.update({ status: 'inactive' })
.eq('id', 123);
```
```typescript
const { data } = await client
.from('users')
.delete()
.eq('id', 123);
```
```typescript
const { data } = await client
.rpc('get_user_stats', { user_id: 123 });
```
--------------------------------
### Next.js Server Authentication Setup
Source: https://github.com/neondatabase/neon-js/blob/main/packages/neon-js/llms.txt
Configure a unified server instance for authentication in a Next.js application. Ensure environment variables for base URL and cookie secret are set.
```typescript
// lib/auth/server.ts - Unified server instance
import { createNeonAuth } from '@neondatabase/neon-js/auth/next/server';
export const auth = createNeonAuth({
baseUrl: process.env.NEON_AUTH_BASE_URL!,
cookies: {
secret: process.env.NEON_AUTH_COOKIE_SECRET!,
sessionDataTtl: 300, // Optional: session data cache TTL in seconds (default: 300 = 5 min)
domain: '.example.com', // Optional: for cross-subdomain cookies
},
});
// app/api/auth/[...path]/route.ts - API handler
import { auth } from '@/lib/auth/server';
export const { GET, POST } = auth.handler();
// middleware.ts - Route protection
import { auth } from '@/lib/auth/server';
export default auth.middleware({ loginUrl: '/auth/sign-in' });
// lib/auth/client.ts - Client-side auth
"use client"
import { createAuthClient } from '@neondatabase/neon-js/auth/next';
export const authClient = createAuthClient();
// Server Components
import { auth } from '@/lib/auth/server';
// Server components using `auth` methods must be rendered dynamically
export const dynamic = 'force-dynamic';
const { data: session } = await auth.getSession();
// Server Actions
import { auth } from '@/lib/auth/server';
await auth.signIn.email({ email, password });
```
--------------------------------
### Configure Neon Auth and Cookie Domain
Source: https://github.com/neondatabase/neon-js/blob/main/examples/cross-domain-cookies/DOCKER-TESTING.md
Sets up Neon Auth credentials and the crucial COOKIE_DOMAIN for cross-subdomain access. The COOKIE_DOMAIN must start with a dot.
```bash
# Neon Auth Configuration
NEON_AUTH_BASE_URL=https://your-project.neon.tech
NEON_AUTH_COOKIE_SECRET=your-secret-at-least-32-characters-long
# Database URL (for main app)
DATABASE_URL=postgresql://user:password@host/database
# Cookie domain - MUST be set for cross-subdomain
COOKIE_DOMAIN=.myapp.local
```
--------------------------------
### Route Handler with NeonAuth Session
Source: https://github.com/neondatabase/neon-js/blob/main/skills/neon-auth-nextjs/SKILL.md
Example of a Next.js API route handler that uses the `auth` instance to get the session and returns user information or an unauthorized error.
```typescript
//app/api/user/route.ts
import { auth } from '@/lib/auth/server';
import { NextResponse } from 'next/server';
export async function GET() {
const { data: session } = await auth.getSession();
if (!session?.user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
return NextResponse.json({ user: session.user });
}
```
--------------------------------
### CSS Import Paths
Source: https://github.com/neondatabase/neon-js/blob/main/CLAUDE.md
Provides examples of how end-users can import CSS from different packages within the neon-js ecosystem, offering convenience for various use cases.
```text
@neondatabase/auth-ui/css - Direct from source
@neondatabase/auth/ui/css - Convenience for auth-only users
@neondatabase/neon-js/ui/css - Convenience for full SDK users
```
--------------------------------
### Auth UI Provider Setup
Source: https://github.com/neondatabase/neon-js/blob/main/examples/neon-auth-orgs-example/README.md
Wraps your application with `NeonAuthUIProvider` in the root layout to enable authentication features. Configure email OTP, redirect URLs, and include user-specific components like `UserButton`.
```tsx
import { NeonAuthUIProvider, UserButton } from "@neondatabase/auth/react";
import { authClient } from "@/lib/auth/client";
{/* header with */}
{children}
```
--------------------------------
### React Router Protected Routes Setup
Source: https://github.com/neondatabase/neon-js/blob/main/skills/neon-auth-react/SKILL.md
Implement protected routes in your React application using React Router. This example shows how to define public, authentication, and protected routes, and how to wrap protected routes with a `ProtectedRoute` component.
```typescript
// routes.tsx
import { Routes, Route } from 'react-router-dom';
export function AppRoutes() {
return (
{/* Public */}
} />
{/* Auth routes */}
} />
{/* Protected */}
} />
} />
);
}
// ProtectedRoute.tsx
function ProtectedRoute({ children }: { children: React.ReactNode }) {
return (
<>
{children}
>
);
}
```
--------------------------------
### Root Layout with AuthProvider (Next.js App Router)
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth-ui/README.md
Example of setting up the root layout in a Next.js App Router project to include the AuthProvider and the auth-ui CSS, ensuring authentication is available throughout the application.
```typescript
import '@neondatabase/auth-ui/css';
import { AuthProvider } from './auth-provider';
export default function RootLayout({ children }) {
return (
{children}
);
}
```
--------------------------------
### Implementing Server Actions for Authentication
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth/NEXT-JS.md
Use the `auth` instance from '@/lib/auth/server' for server-side authentication operations like sign-in and sign-out within Server Actions. This example demonstrates email sign-in and user sign-out with redirection.
```typescript
// app/actions.ts
'use server';
import { auth } from '@/lib/auth/server';
import { redirect } from 'next/navigation';
export async function signIn(formData: FormData) {
const { error } = await auth.signIn.email({
email: formData.get('email') as string,
password: formData.get('password') as string,
});
if (error) return { error: error.message };
redirect('/dashboard');
}
export async function signOut() {
await auth.signOut();
redirect('/auth/sign-in');
}
```
--------------------------------
### Create Dynamic Auth Pages
Source: https://github.com/neondatabase/neon-js/blob/main/skills/neon-auth-nextjs/SKILL.md
Implement dynamic authentication pages using `AuthView` and `authViewPaths`. This setup allows for handling different authentication states (sign-in, sign-up, etc.) dynamically based on the URL path.
```typescript
import { AuthView } from '@neondatabase/auth/react/ui';
import { authViewPaths } from '@neondatabase/auth/react/ui/server';
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 ;
}
```
--------------------------------
### Wrap App with Providers
Source: https://github.com/neondatabase/neon-js/blob/main/skills/neon-auth-react/SKILL.md
Integrate the created Providers component into your application's entry point to enable authentication context across your app. This example uses React Router.
```typescript
import { BrowserRouter } from 'react-router-dom';
import { Providers } from './providers';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')!).render(
);
```
--------------------------------
### Verify Frozen Lockfile Install
Source: https://github.com/neondatabase/neon-js/blob/main/docs/release-runbook.md
Ensure that dependencies can be fetched successfully from JFrog by running a frozen lockfile install. This is a verification step after resolving JFrog proxy issues.
```bash
bun install --frozen-lockfile
```
--------------------------------
### Auth Client Initialization
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth-ui/README.md
Create an authentication client instance using `createAuthClient` from `@neondatabase/auth/next`. This client will be used by the UI components.
```typescript
"use client"
import { createAuthClient } from "@neondatabase/auth/next"
export const authClient = createAuthClient()
```
--------------------------------
### Create Neon.js Client with Environment Variables
Source: https://github.com/neondatabase/neon-js/blob/main/packages/neon-js/README.md
Shows how to initialize the Neon.js client using environment variables for authentication and data API URLs.
```typescript
import { createClient } from '@neondatabase/neon-js';
const client = createClient({
auth: {
url: process.env.NEON_AUTH_URL!,
},
dataApi: {
url: process.env.NEON_DATA_API_URL!,
},
});
```
--------------------------------
### Create Neon.js Client with Explicit Options
Source: https://github.com/neondatabase/neon-js/blob/main/packages/neon-js/README.md
Demonstrates how to create a Neon.js client instance by explicitly providing authentication and data API configurations.
```typescript
import { createClient } from '@neondatabase/neon-js';
const client = createClient({
// Auth configuration
auth: {
url: 'https://your-auth-server.neon.tech/auth',
allowAnonymous: true, // Optional: enable anonymous data access
},
// Data API configuration
dataApi: {
url: 'https://your-data-api.neon.tech/rest/v1',
options: {
db: {
schema: 'public', // Default schema
},
global: {
headers: {
'X-Custom-Header': 'value',
},
},
},
},
});
```
--------------------------------
### Set Up React App Entry Point with Router and Toaster
Source: https://github.com/neondatabase/neon-js/blob/main/examples/react-auth-external-ui/README.md
Configures the main entry point for the React application, setting up React Router for navigation and Sonner for toast notifications.
```tsx
// src/main.tsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { Toaster } from 'sonner';
import './index.css';
import App from './App';
createRoot(document.getElementById('root')!).render(
);
```
--------------------------------
### Basic Client Initialization and Query
Source: https://github.com/neondatabase/neon-js/blob/main/packages/postgrest-js/README.md
Initialize the NeonPostgrestClient with your Data API URL and an API key for authentication. Then, perform a basic select query on a 'users' table.
```typescript
import { NeonPostgrestClient } from '@neondatabase/postgrest-js';
const client = new NeonPostgrestClient({
dataApiUrl: 'https://ep-xxx.apirest.region.aws.neon.build/dbname/rest/v1',
options: {
global: {
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
},
},
db: {
schema: 'public',
},
},
});
// Query your database
const { data, error } = await client
.from('users')
.select('*')
.eq('status', 'active');
```
--------------------------------
### Get Current Session
Source: https://github.com/neondatabase/neon-js/blob/main/packages/neon-js/README.md
Retrieves the current authenticated user's session information.
```typescript
// Get current session
const session = await client.auth.getSession();
```
--------------------------------
### Configure Environment Variables
Source: https://github.com/neondatabase/neon-js/blob/main/examples/neon-auth-orgs-example/README.md
Set up environment variables in `.env.local` for Neon Auth and database connection. Ensure you replace placeholders with your actual Neon project details and generate a secret.
```bash
NEON_AUTH_BASE_URL=https://.neonauth.c-4.us-east-1.aws.neon.tech/neondb/auth
NEON_AUTH_COOKIE_SECRET=<32-byte-base64-secret>
DATABASE_URL=postgresql://neondb_owner:@-pooler.c-4.us-east-1.aws.neon.tech/neondb?sslmode=require
```
--------------------------------
### Initialize Neon Auth Server Instance
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth/NEXT-JS.md
Create a server instance using `createNeonAuth` in Next.js, configuring the base URL and cookie settings for authentication.
```typescript
// lib/auth/server.ts
import { createNeonAuth } from '@neondatabase/auth/next/server';
export const auth = createNeonAuth({
baseUrl: process.env.NEON_AUTH_BASE_URL!,
cookies: {
secret: process.env.NEON_AUTH_COOKIE_SECRET!,
sessionDataTtl: 300, // Optional: session data cache TTL in seconds (default: 300 = 5 min)
domain: ".example.com", // Optional: for cross-subdomain cookies
},
});
```
--------------------------------
### Create Auth Client (Other Frameworks)
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth-ui/README.md
Create a standard auth client for frameworks other than Next.js using `createAuthClient` from `@neondatabase/auth` and providing the authentication URL.
```typescript
"use client"
import { NeonAuthUIProvider } from "@neondatabase/auth-ui"
import { createAuthClient } from "@neondatabase/auth"
const authClient = createAuthClient(process.env.NEXT_PUBLIC_AUTH_URL!)
export function AuthProvider({ children }: { children: React.ReactNode }) {
return (
{children}
)
}
```
--------------------------------
### SupabaseAuthAdapter: Get Session and User
Source: https://github.com/neondatabase/neon-js/blob/main/packages/neon-js/README.md
Retrieves the current user session and user details using the Supabase-compatible API.
```typescript
// Session with data wrapper
const { data: session } = await client.auth.getSession();
const { data: user } = await client.auth.getUser();
```
--------------------------------
### Configure Hosts File (Linux/Mac)
Source: https://github.com/neondatabase/neon-js/blob/main/examples/cross-domain-cookies/DOCKER-QUICKSTART.md
Add entries to the hosts file on Linux or macOS to map local domain names to the loopback address.
```bash
sudo nano /etc/hosts
```
--------------------------------
### NeonAuth Server Actions for Sign In, Sign Up, and Sign Out
Source: https://github.com/neondatabase/neon-js/blob/main/skills/neon-auth-nextjs/SKILL.md
Provides server actions for handling user authentication (sign in, sign up) and sign out using the `auth` instance from '@/lib/auth/server'. Includes redirection after actions.
```typescript
//app/actions/auth.ts
'use server';
import { auth } from '@/lib/auth/server';
import { redirect } from 'next/navigation';
export async function signIn(formData: FormData) {
const { error } = await auth.signIn.email({
email: formData.get('email') as string,
password: formData.get('password') as string,
});
if (error) {
return { error: error.message };
}
redirect('/dashboard');
}
export async function signUp(formData: FormData) {
const { error } = await auth.signUp.email({
email: formData.get('email') as string,
password: formData.get('password') as string,
name: formData.get('name') as string,
});
if (error) {
return { error: error.message };
}
redirect('/dashboard');
}
export async function signOut() {
await auth.signOut();
redirect('/');
}
```
--------------------------------
### Neon.js with SupabaseAuthAdapter
Source: https://github.com/neondatabase/neon-js/blob/main/skills/neon-js-react/SKILL.md
Integrate Neon.js with SupabaseAuthAdapter for Supabase-style authentication methods. Includes client creation and event listener setup.
```typescript
import { createClient, SupabaseAuthAdapter } from '@neondatabase/neon-js';
const neonClient = createClient({
auth: {
url: import.meta.env.VITE_NEON_AUTH_URL,
adapter: SupabaseAuthAdapter(),
},
dataApi: {
url: import.meta.env.VITE_NEON_DATA_API_URL,
},
});
// Supabase-style methods
await neonClient.auth.signUp({ email, password, options: { data: { name } } });
await neonClient.auth.signInWithPassword({ email, password });
await neonClient.auth.signInWithOAuth({ provider: 'google', options: { redirectTo } });
const { data: session } = await neonClient.auth.getSession();
await neonClient.auth.signOut();
// Event listener
neonClient.auth.onAuthStateChange((event, session) => {
console.log(event); // 'SIGNED_IN', 'SIGNED_OUT', 'TOKEN_REFRESHED'
});
```
--------------------------------
### Configure Hosts File (Windows)
Source: https://github.com/neondatabase/neon-js/blob/main/examples/cross-domain-cookies/DOCKER-QUICKSTART.md
Add entries to the hosts file on Windows as Administrator to map local domain names to the loopback address.
```bash
Open C:\\Windows\\System32\\drivers\\etc\\hosts as Administrator
```
--------------------------------
### View Specific Docker Compose Service Logs
Source: https://github.com/neondatabase/neon-js/blob/main/examples/cross-domain-cookies/DOCKER-TESTING.md
Monitor the logs of a particular service within your Docker Compose setup.
```bash
docker-compose logs -f main-app
```
```bash
docker-compose logs -f admin-portal
```
```bash
docker-compose logs -f nginx
```
--------------------------------
### Docker Setup for Cross-Subdomain Testing
Source: https://github.com/neondatabase/neon-js/blob/main/examples/nextjs-admin-portal/README.md
Configure and run the admin portal using Docker Compose to test cross-subdomain cookie sharing. This involves setting up environment variables, modifying the hosts file, and building/starting the Docker services.
```bash
# From monorepo root
cd examples/cross-domain-cookies
cp .env.docker.example .env
# Edit .env with your credentials
# Add to /etc/hosts (Linux/Mac) or C:\\Windows\\System32\\drivers\\etc\\hosts (Windows)
127.0.0.1 myapp.local
127.0.0.1 app.myapp.local
127.0.0.1 admin.myapp.local
# Build and start services
docker-compose up --build
```
--------------------------------
### User Authentication with Neon.js
Source: https://github.com/neondatabase/neon-js/blob/main/packages/neon-js/llms.txt
Perform sign up, sign in (email/social), get session, and sign out operations using the Neon.js client.
```typescript
// Sign up
await client.auth.signUp.email({
email: 'user@example.com',
password: 'secure-password',
name: 'John Doe',
});
// Sign in with email
await client.auth.signIn.email({
email: 'user@example.com',
password: 'secure-password',
});
// Sign in with OAuth
await client.auth.signIn.social({
provider: 'google',
callbackURL: '/dashboard',
});
// Get session
const session = await client.auth.getSession();
// Sign out
await client.auth.signOut();
```
--------------------------------
### Local Development with Local neon-js
Source: https://github.com/neondatabase/neon-js/blob/main/examples/nextjs-phone-login/README.md
Instructions for developing with a local version of the `@neondatabase/auth` package. This is useful for testing unreleased features.
```bash
# From the neon-js repo root
bun install
bun run build # Build all packages
cd examples/nextjs-phone-login
bun dev
```
--------------------------------
### Update Neon.js Client Initialization
Source: https://github.com/neondatabase/neon-js/blob/main/packages/neon-js/README.md
Demonstrates how to update the client initialization code when migrating from Supabase to Neon, specifying the `SupabaseAuthAdapter` and new environment variables.
```diff
- import { createClient } from '@supabase/supabase-js';
+ import { createClient, SupabaseAuthAdapter } from '@neondatabase/neon-js';
- export const client = createClient(
- import.meta.env.VITE_SUPABASE_URL,
- import.meta.env.VITE_SUPABASE_ANON_KEY
- );
+ export const client = createClient({
+ auth: {
+ adapter: SupabaseAuthAdapter(), // Must call as function!
+ url: import.meta.env.VITE_NEON_AUTH_URL,
+ },
+ dataApi: {
+ url: import.meta.env.VITE_NEON_DATA_API_URL,
+ },
+ });
```
--------------------------------
### Get Active Organization ID from Session
Source: https://github.com/neondatabase/neon-js/blob/main/examples/neon-auth-orgs-example/README.md
Retrieves the active organization ID from the session object. Returns null if not found or not a string.
```typescript
// src/lib/auth/session.ts
export function getActiveOrgId(session: {
session: Record;
}): string | null {
const orgId = session.session.activeOrganizationId;
return typeof orgId === "string" ? orgId : null;
}
```
--------------------------------
### Sign Up with Email
Source: https://github.com/neondatabase/neon-js/blob/main/packages/neon-js/README.md
Registers a new user with email and password. Optionally, you can provide user metadata.
```typescript
await client.auth.signUp.email({
email: 'user@example.com',
password: 'secure-password',
name: 'John Doe',
});
```
--------------------------------
### Build Workspace Packages
Source: https://github.com/neondatabase/neon-js/blob/main/examples/neon-auth-magic-link-example/README.md
Build the necessary workspace packages for the project using Bun.
```bash
bun run build
```
--------------------------------
### Next.js Server-Side Authentication Setup
Source: https://github.com/neondatabase/neon-js/blob/main/CLAUDE.md
Configure server-side authentication for Next.js applications using createNeonAuth. This includes setting up base URL, cookies, and middleware.
```typescript
// lib/auth/server.ts
import { createNeonAuth } from '@neondatabase/auth/next/server';
export const auth = createNeonAuth({
baseUrl: process.env.NEON_AUTH_BASE_URL!,
cookies: {
secret: process.env.NEON_AUTH_COOKIE_SECRET!,
sessionDataTtl: 300, // Optional: session data cache TTL in seconds (default: 300 = 5 min)
domain: '.example.com', // Optional: for cross-subdomain cookies
},
});
// api/auth/[...path]/route.ts
import { auth } from '@/lib/auth/server';
export const { GET, POST } = auth.handler();
// middleware.ts
import { auth } from '@/lib/auth/server';
export default auth.middleware({ loginUrl: '/auth/sign-in' });
```
--------------------------------
### Simple SELECT Query
Source: https://github.com/neondatabase/neon-js/blob/main/packages/neon-js/llms.txt
Perform a basic SELECT query to retrieve specific columns from a table. No special setup is required beyond having a client instance.
```typescript
// Simple select
const { data } = await client.from('users').select('id, name, email');
```
--------------------------------
### Configuring SignInForm Props
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth-ui/llms.txt
Example of passing props to the SignInForm component to control redirection and OAuth callback URLs, as well as applying custom container styling.
```typescript
```
--------------------------------
### Run E2E Tests Locally
Source: https://github.com/neondatabase/neon-js/blob/main/AGENTS.md
Execute end-to-end tests locally after building the packages and example app. This command filters the E2E tests for CI execution.
```bash
pnpm run --filter e2e test:ci
```
--------------------------------
### Build and Link Local Packages
Source: https://github.com/neondatabase/neon-js/blob/main/DEVELOPMENT.md
Execute these commands to build locally developed packages and link them for use in your project.
```bash
pnpm run build
pnpm run link:neon-js
```
--------------------------------
### Next.js Server Components and Server Actions
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth/llms.txt
Demonstrates how to fetch session data in dynamically rendered Server Components and perform authentication actions like signing in using email and password within Server Actions.
```typescript
// Server Components
import { auth } from '@/lib/auth/server';
// Server components using `auth` methods must be rendered dynamically
export const dynamic = 'force-dynamic';
const { data: session } = await auth.getSession();
```
```typescript
// Server Actions
import { auth } from '@/lib/auth/server';
await auth.signIn.email({ email, password });
```
--------------------------------
### Get JWT Token
Source: https://github.com/neondatabase/neon-js/blob/main/skills/neon-js-react/SKILL.md
Retrieves the current JSON Web Token (JWT) for the authenticated user using `neonClient.auth.getJWTToken()`. This token can be used for external API calls.
```typescript
const token = await neonClient.auth.getJWTToken();
// Use for external API calls
const response = await fetch('/api/external', {
headers: { Authorization: `Bearer ${token}` },
});
```
--------------------------------
### CSS Layering Example
Source: https://github.com/neondatabase/neon-js/blob/main/packages/auth-ui/llms.txt
Demonstrates how to override @neondatabase/auth-ui's default --primary CSS variable with your own value. User-defined unlayered CSS always takes precedence.
```css
/* This ALWAYS wins over auth-ui's default --primary */
:root {
--primary: oklch(0.55 0.25 250);
}
```