Authentication Setup - Next-Auth
This document explains how to set up authentication in your Next.js 14 application using NextAuth and Supabase. We will cover two methods: Magic Links and Google Authentication.
Configuration
Ensure you have the following environment variables configured in your .env file:
For Magic Links
# NextAuth Magic Link
EMAIL_SERVER_USER=<your_email_server_user>
EMAIL_SERVER_PASSWORD=<your_email_server_password>
EMAIL_SERVER_HOST=sandbox.smtp.mailtrap.io
EMAIL_SERVER_PORT=587
EMAIL_FROM=noreply@example.com
For Google Authentication
# Social Login
GOOGLE_CLIENT_ID=<your_google_client_id>
GOOGLE_CLIENT_SECRET=<your_google_client_secret>
CALLBACK_URL='/admin/customers'
Setting Up NextAuth
NextAuth is a complete open-source authentication solution for Next.js applications. You can configure it in the `/app/api/auth/[...nextauth]/route.js` file.
Authentication Methods
- Magic Links
- Google Authentication
Magic Links
Magic Links allow users to sign in using a link sent to their email. This method is simple and secure, as it does not require a password.
Environment Configuration: Make sure your `.env` file has the correct email server settings:
EMAIL_SERVER_USER=<your_email_server_user>
EMAIL_SERVER_PASSWORD=<your_email_server_password>
EMAIL_SERVER_HOST=sandbox.smtp.mailtrap.io
EMAIL_SERVER_PORT=587
EMAIL_FROM=noreply@example.com
When a user tries to log in, they will receive an email with a link. Clicking the link will log them in automatically.
Google Authentication
Google Authentication allows users to log in using their Google account. This is convenient and secure, leveraging Google's authentication mechanisms.
Environment Configuration: Ensure your `.env` file includes your Google client credentials:
GOOGLE_CLIENT_ID=<your_google_client_id>
GOOGLE_CLIENT_SECRET=<your_google_client_secret>
CALLBACK_URL='/admin/customers'
When a user tries to log in, they will be redirected to Google's login page. After authenticating with Google, they will be redirected back to your application.
Conclusion
Setting up authentication in your Next.js 14 application is straightforward with NextAuth. Whether you choose Magic Links or Google Authentication, NextAuth provides a flexible and secure solution. Make sure to configure your environment variables correctly and set up the providers in your `authOptions`.
For more detailed information, you can refer to the NextAuth.js documentation.