How to Use NextAuth.js for Authentication in Next.js

How to Use NextAuth.js for Authentication in Next.js

NextAuth.js is a powerful authentication library designed to seamlessly integrate with Next.js applications. With its flexible configuration and support for various authentication providers, it allows developers to implement secure user authentication with minimal effort. In this guide, we will explore how to set up NextAuth.js for authentication in your Next.js project.

Step 1: Install NextAuth.js

To get started, you need to install NextAuth.js in your Next.js application. Open your terminal, navigate to your project directory, and run the following command:

npm install next-auth

This command installs NextAuth.js and its dependencies, allowing you to use it in your application.

Step 2: Create an API Route for Authentication

NextAuth.js requires an API route to handle authentication requests. To set this up, create a new directory called pages/api/auth and add a file named [...nextauth].js. Your file structure should look like this:

pages/
  └── api/
      └── auth/
          └── [...nextauth].js

In the [...nextauth].js file, you will configure NextAuth.js. Here's a basic example of how to set it up:

import NextAuth from "next-auth";
import Providers from "next-auth/providers";
export default NextAuth({
  providers: [
    Providers.Google({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    // Add additional providers as needed
  ],
  // Add a database or adapter if necessary
  session: {
    jwt: true,
  },
  pages: {
    signIn: '/auth/signin',
    // You can customize additional pages here
  },
});

Make sure to replace GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET with your actual credentials, which you can obtain by creating a project in the Google Cloud Console. Don't forget to add these credentials to your environment variables.

Step 3: Configure Environment Variables

Next, add your authentication provider keys to your environment variables. Create a .env.local file in the root of your project if you haven’t already, and add the following lines:

GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret

Replace your_google_client_id and your_google_client_secret with your actual values. This file should never be shared or committed to version control, as it contains sensitive information.

Step 4: Implement Sign-In and Sign-Out

Now that you have your API route set up, you can start implementing sign-in and sign-out functionality in your application. To do this, you can use the signIn and signOut methods provided by NextAuth.js.

For example, to create a button for signing in or out, you can use the following code:

import { signIn, signOut, useSession } from "next-auth/react";
const AuthButton = () => {
  const { data: session } = useSession();
return session ? (
    
  ) : (
    
  );
};

This code checks the current session. If a user is signed in, it shows a "Sign Out" button; otherwise, it shows a "Sign In with Google" button.

Step 5: Protecting Routes

To protect your routes and ensure only authenticated users can access certain pages, you can create a higher-order component (HOC) or a custom hook. Here's an example of how to create a simple protected route:

import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
import { useEffect } from "react";
const ProtectedRoute = ({ children }) => {
  const { data: session, status } = useSession();
  const router = useRouter();
useEffect(() => {
    if (status === "loading") return; // Do nothing while loading
    if (!session