npm package: @scaffit/nextauth
Description: NextAuth.js authentication setup for Next.js projects
Author: Santosh Hanumaiah Ranganatha
Latest version: 1.0.1

# @scaffit/nextauth

NextAuth.js authentication setup for Next.js projects with OAuth providers.

## Features

- **OAuth Providers** - Google, GitHub, Discord, Twitter
- **Credentials Support** - Email/Password authentication
- **Database Support** - Optional database sessions with Prisma, MongoDB, MySQL, PostgreSQL
- **Type-Safe** - Full TypeScript support
- **Client Utilities** - React hooks and helpers
- **Middleware** - Automatic route protection

## Installation

### Option 1: Using Scaffit CLI (Recommended)
```bash
# Add NextAuth scaffold (no installation needed!)
npx scaffit add nextauth
```

### Alternative: Global Installation
```bash
# Install CLI globally
npm install -g scaffit

# Add NextAuth scaffold
scaffit add nextauth
```

### Option 2: Direct npm package usage
```bash
# Install scaffold directly
npm install @scaffit/nextauth

# Use in your code
import { setupNextAuth, previewNextAuth } from '@scaffit/nextauth';

// Setup NextAuth with custom options
const result = await setupNextAuth({
  providers: ['google', 'github'],
  database: true,
  databaseType: 'prisma',
  projectRoot: './my-project'
});

// Preview changes before applying
const preview = await previewNextAuth({
  providers: ['google', 'github'],
  database: true
});
```

**Note**: Both approaches require `@scaffit/core` to be installed (automatically handled).

## Configuration

The scaffold creates several files:

### API Route
`app/api/auth/[...nextauth]/route.ts` - NextAuth API handler

### Configuration
`lib/auth.ts` - NextAuth configuration with providers and callbacks

### Middleware
`middleware.ts` - Route protection middleware

### Client Utilities
`lib/auth-client.ts` - React hooks and helpers

### Environment Variables
Added to `.env.example`:
```env
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your-secret-here

# Google OAuth
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=

# GitHub OAuth
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
```

## Usage

### Server Components
```typescript
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';

export default async function Page() {
  const session = await getServerSession(authOptions);
  
  if (!session) {
    return <p>Not authenticated</p>;
  }
  
  return <p>Hello {session.user?.name}!</p>;
}
```

### Client Components
```typescript
'use client';
import { useAuth, SessionProvider } from '@/lib/auth-client';

function UserProfile() {
  const { session, isAuthenticated } = useAuth();
  
  if (!isAuthenticated) {
    return <p>Loading...</p>;
  }
  
  return <p>Hello {session?.user?.name}!</p>;
}

export default function Layout({ children }) {
  return (
    <SessionProvider>
      {children}
    </SessionProvider>
  );
}
```

### Sign Out
```typescript
import { signOut } from '@/lib/auth-client';

await signOut('/auth/signin');
```

## OAuth Providers Setup

### Google
1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Create a new project or select existing
3. Enable Google+ API
4. Create OAuth 2.0 credentials
5. Add authorized redirect URIs: `http://localhost:3000/api/auth/callback/google`
6. Copy Client ID and Secret to `.env`

### GitHub
1. Go to [GitHub Developer Settings](https://github.com/settings/developers)
2. Create new OAuth App
3. Set Authorization callback URL: `http://localhost:3000/api/auth/callback/github`
4. Copy Client ID and Secret to `.env`

### Discord
1. Go to [Discord Developer Portal](https://discord.com/developers/applications)
2. Create new application
3. Add OAuth2 redirect: `http://localhost:3000/api/auth/callback/discord`
4. Copy Client ID and Secret to `.env`

### Twitter
1. Go to [Twitter Developer Portal](https://developer.twitter.com/en/portal/dashboard)
2. Create a new project and app
3. Set callback URL: `http://localhost:3000/api/auth/callback/twitter`
4. Copy Client ID and Secret to `.env`

## Database Sessions

### With Prisma
```bash
# Install Prisma
npm install @prisma/client

# Generate Prisma schema
npx prisma generate
```

### With MongoDB
```bash
# Install MongoDB adapter
npm install @next-auth/mongodb-adapter
```

## Customization

### Custom Sign In Page
Create `app/auth/signin/page.tsx`:
```typescript
import { getProviders, signIn } from 'next-auth/react';

export default async function SignIn() {
  const providers = await getProviders();
  
  return (
    <div>
      {Object.values(providers).map((provider) => (
        <button key={provider.name} onClick={() => signIn(provider.id)}>
          Sign in with {provider.name}
        </button>
      ))}
    </div>
  );
}
```

## License

MIT