This project demonstrates how to implement GitHub OAuth authentication in a Next.js application using the better-auth library.
- GitHub OAuth authentication
- User session management
- Responsive UI with sign-in/sign-out functionality
- Clone the repository
- Install dependencies:
npm install
- Create a
.env.local
file with your GitHub OAuth credentials:GITHUB_CLIENT_ID=your_github_client_id GITHUB_CLIENT_SECRET=your_github_client_secret
- Go to GitHub Developer Settings
- Click on "New OAuth App"
- Fill in the application details:
- Application name: Your app name
- Homepage URL: http://localhost:3000
- Authorization callback URL: http://localhost:3000/api/auth/callback/github
- Register the application
- Copy the Client ID and generate a new Client Secret
- Add these credentials to your
.env.local
file
npm run dev
Visit http://localhost:3000 to see the application running.
The authentication is implemented using the following components:
- API Route:
/app/api/auth/[...all]/route.ts
handles the authentication API endpoints - Auth Configuration:
/app/auth.ts
configures the better-auth instance with GitHub provider - Auth Client:
/app/auth-client.ts
creates the client-side auth client - Auth Provider:
/app/providers/AuthProvider.tsx
provides authentication context to the application - Auth Button:
/app/components/AuthButton.tsx
implements the sign-in/sign-out UI
- User clicks the "Sign in with GitHub" button
- They are redirected to GitHub to authorize the application
- After authorization, they are redirected back to the application
- The application receives the authorization code and exchanges it for an access token
- The access token is used to fetch the user's profile information
- The user is signed in and their profile information is displayed
To learn more about Next.js, take a look at the following resources:
- Next.js Documentation - learn about Next.js features and API.
- Learn Next.js - an interactive Next.js tutorial.
- Better Auth Documentation - learn about Better Auth features and API.