# Auth.js (next-auth)

## Simple ID OAuth Provider Integration Guide for Auth.js

This guide explains how to integrate Simple ID as a custom OAuth 2.0 provider in your Auth.js (NextAuth.js) application.

### Prerequisites

* Node.js 16.13.0 or later
* An Auth.js project set up in your application
* A registered application in Simple ID with:
  * Client ID
  * Client Secret
  * Configured redirect URIs

### Implementation Steps

#### 1. Install Required Dependencies

```bash
npm install next-auth
# or
yarn add next-auth
```

#### 2. Create Custom Provider Configuration

Create a new file `simple-id.ts` in your project's auth providers directory:

```typescript
import type { OAuthConfig, OAuthUserConfig } from 'next-auth/providers'

export interface SimpleIDProfile extends Record<string, any> {
  sub: string
  email: string
  // Add other profile fields as needed
}

export default function SimpleID<P extends SimpleIDProfile>(
  config: OAuthUserConfig<P>
): OAuthConfig<P> {
  return {
    id: 'simple-id',
    name: 'Simple ID',
    type: 'oauth',
    wellKnown: 'https://api.simplepay.ai/oidc/.well-known/openid-configuration',
    authorization: {
      params: {
        scope: 'openid email offline_access',
        // Add other scopes as needed
      },
    },
    idToken: true,
    checks: ['pkce', 'state'],
    profile(profile) {
      return {
        id: profile.sub,
        email: profile.email,
        // Map other profile fields as needed
      }
    },
    ...config,
  }
}
```

#### 3. Configure Auth.js

Update your Auth.js configuration file (`[...nextauth].ts` or similar):

```typescript
import NextAuth from 'next-auth'
import SimpleID from './providers/simple-id'

export default NextAuth({
  providers: [
    SimpleID({
      clientId: process.env.SIMPLE_ID_CLIENT_ID,
      clientSecret: process.env.SIMPLE_ID_CLIENT_SECRET,
    }),
  ],
  // Additional configuration options
  callbacks: {
    async jwt({ token, account }) {
      // Persist the OAuth access_token and refresh_token to the token right after signin
      if (account) {
        token.accessToken = account.access_token
        token.refreshToken = account.refresh_token
      }
      return token
    },
    async session({ session, token }) {
      // Send properties to the client
      session.accessToken = token.accessToken
      return session
    },
  },
})
```

#### 4. Environment Configuration

Add the following variables to your `.env.local` file:

```env
SIMPLE_ID_CLIENT_ID=your_client_id
SIMPLE_ID_CLIENT_SECRET=your_client_secret
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your_secret_key
```

#### 5. Add Sign-in Button

Add the sign-in button to your React component:

```typescript
import { signIn } from 'next-auth/react'

export default function SignInButton() {
  return (
    <button
      onClick={() => signIn('simple-id', { callbackUrl: '/dashboard' })}
      className="login-button"
    >
      Sign in with Simple ID
    </button>
  )
}
```

### Available Scopes

Simple ID supports the following scopes:

* `openid`
* `email`
* `offline_access`
* `app:read`
* `app:write`
* `app.address:read`
* `app.address:write`
* `app.cryptocurrency:read`
* `app.cryptocurrency:write`
* `billing:read`
* `invoice:read`
* `product:write`

### Error Handling

Add error handling in your Auth.js configuration:

```typescript
// In your [...nextauth].ts
export default NextAuth({
  // ... other config
  callbacks: {
    async signIn({ account, profile }) {
      if (account && profile) {
        return true
      }
      return false
    },
  },
  events: {
    async signIn(message) {
      // Handle successful sign in
    },
    async error(error) {
      console.error('Auth error:', error)
    },
  },
})
```

### Security Considerations

1. Always store sensitive credentials in environment variables
2. Enable PKCE (Proof Key for Code Exchange) for added security
3. Implement proper error handling and logging
4. Use HTTPS in production
5. Regularly rotate your client secrets

### Debugging Tips

1. Enable debug mode in Auth.js:

```typescript
export default NextAuth({
  debug: process.env.NODE_ENV === 'development',
  // ... rest of your config
})
```

2. Check the browser console and server logs for error messages
3. Verify your redirect URIs are correctly configured in Simple ID
4. Ensure all required scopes are properly requested

### Additional Resources

* [Auth.js Documentation](https://authjs.dev/)
* [OAuth 2.0 Specifications](https://oauth.net/2/)
* Simple ID Documentation (Add your documentation URL)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dev.simplepay.ai/docs/simple-id/integrations/auth.js-next-auth.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
