How to Add Authentication to Your Next.js App with Auth.js



This content originally appeared on DEV Community and was authored by Kpeale Legbara

Have you ever wanted to add authentication to your Next.js app but didn’t know where to start?

In this article, I’ll walk you through how to add authentication to your Next.js application using Auth.js, formerly known as NextAuth.

By the end of this tutorial, you’ll be able to:

  • Understand Authentication using Auth.js in Next.js
  • Sign in with your Google account

Authentication is very common in almost all the applications we use on our mobile phones or laptops. Most users rarely create a new profile in any app when they can sign-up using their Google account or Github account. In this article, we will be looking at how to grant authentication to a user using Auth.js.

What is Auth.js?

Auth.js is a complete open-source authentication solution for JavaScript applications. It’s flexible and supports multiple providers, including Google, GitHub, Discord, and more..

Why use Auth.js in a Next.js application?

  • Easy and simple to use: One main reason developers go for Auth.js is how simple the process of authentication is with Auth.js.
  • Secure Session Management: Auth.js handles secure session management, including the use of encrypted cookies or JSON Web Tokens (JWTs) to maintain user state across requests.
  • Customization and Flexibility: Auth.js allows for significant customization this means developers can tailor login pages and sign-out processes to match their application’s design and requirements.
  • Built-in Security Features: Auth.js incorporates security best practices, such as handling sensitive data securely.
  • Ease of Integration with Next.js: Auth.js offers seamless compatibility with Next.js features like the App Router and Pages Router.
  • Open-Source and Community Support:Auth.js is an open-source project. It has a large and active community, providing extensive documentation, tutorials, and support for developers.

Getting Started

To follow along, you should have a basic understanding of React and Next.js. You should also have a Next.js project set up. If you don’t, you can quickly create one using:

npx create-next-app@latest

Follow the prompts to install Next.js in your project.For this tutorial, I’ll be using the App Router (introduced in Next.js 13+). Auth.js supports both the App Router and Pages Router, but in this guide, we’ll use the App Router.

Step 1: Installing and Setting Up Auth.js

After installing Next.js in your project. The next thing is to install Auth.js. Run this command to install the Auth.js dependencies:

npm install next-auth@beta

Step 2: Set Up Environment

The only environment variable that is mandatory is the AUTH_SECRET. This is a random value used by the library to encrypt tokens and email verification hashes. You can generate one by running the command below in your terminal:

npx auth secret

After running the command, a file with the name env.local will be created for you. Inside the env.local, you will see the AUTH_secret.

Step 3: Set Up the Auth Route

A. Begin by creating a new auth.ts file at your project’s root with the following content.

import NextAuth from "next-auth"
export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [],
})

B. The next step is to add a Route Handler. We’ll do this by creating an api folder inside the app folder. Then, create another folder named auth inside the api folder. Within the auth folder, create a folder called […nextauth]. Inside […nextauth], add a file named route.ts. Insert the following code into route.ts:

import { handlers } from "@/auth"

export const { GET, POST } = handlers

C. The final step in this setup is to add an optional Middleware to keep the session alive, which will refresh the session expiry each time it is called. To do this, create a middleware.ts file at the root and include the code below:

export { auth as middleware } from "@/auth"

We have finished the basic authentication setup! Now, we will go to setup the authentication methods.

Setup Authentication Methods

Auth.js comes with over 80 providers preconfigured. You can choose any provider in their documentation here to get a walk-through, but for the purpose of this article, we will use Google.

  1. Register OAuth App in Google’s dashboard: First, we will set up an OAuth application on the Google Developers Dashboard. Click on this link to take you to Google Developers Dashboard.

  2. Create an account if you do not have a Google account. if you have one, then sign-in.

  3. Click on Create a new project. Fill in a project name and click Create. Go to library on the left menu and search for “Google + API. If you cannot find it then click on this link, it will direct you to where you will create the OAuth for Google. On the left menu, click on “consent screen” . You will be asked some basic information, fill it.

  4. Now the consent screen is up, click on credentials so we can add the credentials created to our Next.js app. Click on create credentials and also click on create OAUTH client id. The fill the following questions with the answers below:

Click on Create. A pop up will come up showing you the client id and client secrete. Copy the details and add them to env.local.

GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
NEXTAUTH_SECRET=your-random-secret

Setup Provider

A. Let’s enable Google as a sign in option in our Auth.js configuration. You’ll have to import the Google provider from the package and pass it to the providers array we setup earlier in the Auth.js config file. Copy the code below:


import NextAuth from 'next-auth';
import Google from 'next-auth/providers/google';

export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [
    Google({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
  ],
});

B. Add the handlers which NextAuth returns to your api/auth/[…nextauth]/route.ts file so that Auth.js can run on any incoming request. Copy the code below:


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

Add Signin Button

Next, we will add a sign-in button somewhere in our application so it will trigger Auth.js sign- in when clicked. You can now use the Sign-in from auth.js in your button like the example below:


'use client';
import { NavLinks } from '@/constant/constant';
import Link from 'next/link';
import { HiBars3BottomRight } from 'react-icons/hi2';
import { LuNetwork } from 'react-icons/lu';
import { signIn } from 'next-auth/react'

const Nav = () => {

  return (
    <div
      className={transition-all ${
        navBg ? 'bg-white dark:bg-gray-900 shadow-md' : 'fixed'
      } duration-200 h-[12vh] z-[10000]  fixed w-full}
    >
      <div className='flex items-center h-full justify-between w-[92%] mx-auto'>
        <div className='flex items-center sm:space-x-20'>
          {/* logo */}
          <div className='flex items-center space-x-2'>
            <div className='w-10 h-10 bg-cyan-800 dark:bg-white  rounded-full flex items-center justify-center flex-col'>
              <LuNetwork className='w-5 h-5 text-white dark:text-black' />
            </div>
            <h1 className='text-xl hidden sm:block md:text-2xl text-cyan-800 dark:text-white font-bold'>
              Devhire
            </h1>
          </div>

          <div className='hidden lg:flex items-center space-x-10'>
            {NavLinks.map((link) => (
              <Link
                href={link.url}
                key={link.id}
                className='text-base hover:text-cyan-700 dark:hover:text-cyan-200 font-medium transition-all duration-200'
              >
                <p>{link.label}</p>
              </Link>
            ))}
          </div>
        </div>
        <div className='flex items-center space-x-4'>

            <button
              className='px-8 py-2.5 text-xs sm:text-sm rounded-lg cursor-pointer bg-gray-100 hover:bg-gray-300 transition-all duration-300  dark:bg:gray-700 dark:hover:bg-gray-900 '
              type='submit'
              onClick={() => signIn('google')}
            >
              Login / Register
            </button>
            <button className='px-8 py-2.5 text-xs sm:text-sm hidden sm:block rounded-lg cursor-pointer bg-cyan-700 hover:bg-cyan-900 transition-all duration-300'>
              Job Post
            </button>

          <HiBars3BottomRight
            className='w-8 h-8 cursor-pointer text-black lg:hidden dark:text-white'

          />
        </div>
      </div>
    </div>
  );
};

export default Nav;

In the example above, I created a nav component and added the sign-in from Auth.js.

Conclusion

Auth.js is very easy to use and I am sure you can say the same after reading this article and following the steps outlined in the article. If you have any questions, please ask them in the comments section below. You should also check out their documentation, by clicking on this link.


This content originally appeared on DEV Community and was authored by Kpeale Legbara