sofiDev img

Nurture Tech

How to Add NextAuth in Next.js 14?

With the major update in Next.js 14, including a new folder structure, setting up NextAuth has changed significantly. If you're confused about how to integrate NextAuth into your Next.js 14 application, this guide will help you through the process step-by-step.

Step 1: Install NextAuth

Begin by installing NextAuth and its required dependencies using the following command:

npm install next-auth

This will add the necessary packages to your project, allowing you to set up authentication in your Next.js app.

Step 2: Create an API Route for NextAuth

In Next.js 14, the folder structure has changed. To configure NextAuth, you need to create an API route. Create a new file at /app/api/auth/[...nextauth]/route.js with the following content:

This configuration sets up Google as an OAuth provider. You can replace Google with any provider supported by NextAuth.

Step 3: Configure Environment Variables

NextAuth requires several environment variables to function correctly. Add the following variables to your .env file:


GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
NEXTAUTH_SECRET=your-nextauth-secret
NEXTAUTH_URL=your-site-url-base-path
AUTH_TRUST_HOST=true
			

Replace your-client-id, your-client-secret, and your-nextauth-secret with your actual credentials.

Step 4: Deployment Issues

There are some issues with the deployment, to bypass those you need to follow 2 more steps
1) Add a NEXTAUTH_SECRET to the env and make sure to add that into your next auth handler (The secret key can be any unique number of your choice).
2) Add a NEXTAUTH_URL to your env file it should be the base path of your domain.

Here is how to add NEXTAUTH_SECRET to your provider:

Step 5: Get Session information

You need to wrap your app children in a SessionProvider, after that we can target the session data through the session provider

Step 6: Use sign in function

Now your setup is completed just call the function signIn('google'), on your login button import that from session provider, and ALL SET

OUR SERVICES

Need Help with Integration?

Hire us to ensure your NextAuth setup is done right!

Hirings