NextAuth.js with Next.js 15: Custom Web Development Guide

NextAuth.js with Next.js 15: Custom Web Development Guide NextAuth.js with Next.js 15: Custom Web Development Guide

In the digital age, securing your applications is not just a necessity—it’s imperative. As custom web development evolves, so do the tools that enhance security and user experience.

NextAuth.js is a beacon for developers seeking to implement authentication with ease and efficiency. Whether you’re adding authentication for the first time or upgrading to keep pace with modern best practices, this blog will walk you through the process step-by-step.

What is NextAuth?

NextAuth is an open-source authentication solution for Nextjs apps. It is slowly being built to offer solutions for all frameworks or libraries on custom web development. You can learn more about the details on the Authjs website.

You can consider NextAuth as a middleman between your app and proven authentication systems. So rather than re-inventing the wheel, you can incorporate this solution into yours and continue developing your app.

Why Use NextAuth.js Version 5?

Version 5 of NextAuth.js introduces several enhancements that make it an ideal choice for the modern web applications. It is designed to leverage the latest features of Next.js, including the App Router, ensuring seamless integration and improved routing capabilities.

How to Setup the Project?

Step 1: Initial Setup

For this guide, we will be using the latest version of Next.js (v 15.1.6) with app router. Start by creating a new Next.js project using these commands in the terminal:

npx create-next-app@latest my-nextauth-app
cd my-nextauth-app

Install NextAuth.js in your project to get started with the setup:

npm install next-auth@beta

Step 2: Configure Environment Variables for Security

Generate a secure AUTH_SECRET which will encrypt tokens and session data using the following command:

npx auth secret

Add this generated secret to your .env.local:

AUTH_SECRET=your_generated_secret

Step 3: Obtaining Google API Credentials

For this guide, we will be using Google as a provider to authenticate users. To use Google as a provider, you need to set up credentials through Google Cloud Console:

  • Create a project in the Google Cloud Console.
  • Navigate to Credentials, click on “Create Credentials”, and select “OAuth client ID”.
  • Configure the consent screen with the necessary information about your application.
  • Set the authorized redirect URI as http://localhost:3000/api/auth/callback/google for development.
    After setting these, copy the Client ID and Client Secret provided by Google and add them to your .env.local:

GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret

Step 4: Configuring NextAuth.js for Google Authentication:

To set up authentication using Google, create a new file named auth.js at the root of your application. This file will contain all necessary configurations for your authentication providers.

Open the auth.js file and configure NextAuth.js to use Google as an authentication provider. You will need to import NextAuth and the GoogleProvider module from next-auth/providers/google. Here’s how to set it up:

import NextAuth from ‘next-auth’
import GoogleProvider from ‘next-auth/providers/google’

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET
    })
  ],
  secret: process.env.AUTH_SECRET
})

Step 5: Add a Route Handler:

To integrate NextAuth.js seamlessly, we need the API routes that our authentication functions will use. We will add it under: /app/api/auth/[…nextauth]/route.js

import { handlers } from ‘@/auth’
export const { GET, POST } = handlers

Step 6: Implement a Protected Component

Create a new protected component under /components folder using the following code:

“use client”;

import { useSession, signIn } from “@/auth”;
export default function Protected() {
  const { data: session, status } = useSession({
    required: true,
    onUnauthenticated() {
      signIn(); // Triggers signing in if not authenticated
    }
  });

  if (status === “loading”) {
    return

Loading…

;
  }

  return (
   

     
     

Welcome, {session.user.name}!


   


  );
}

In this component, If the user is not authenticated (onUnauthenticated), it automatically triggers the signIn function, redirecting the user to the login screen. This ensures that only authenticated users can access the page.

Since it is a client component, we need to wrap all client components in SessionProvider from next-auth/react. This would allow us to use the useSession hook in our components.

Conclusion

By following these steps, you’ve successfully integrated NextAuth.js into your Next.js application, enabling Google authentication for your users.

This setup enhances your application’s security and usability. As you move forward, you can integrate other custom web development providers into it, expanding the versatility of your app. Happy coding!

If you need further help, you can contact us at [email protected]. We will schedule a free consultation session to explore how Xavor can assist you in this matter.

Add a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use