Adding Authentication to Next.js Project Using Auth.js: A Step-by-Step Guide

Vinish Bhaskar

Published on:Oct 29 2024

Adding Authentication to Next.js Project Using Auth.js: A Step-by-Step Guide

In today's world, Authentication is an important part of web applications as it ensures that only authorized people can access specific resources or perform specific actions. It helps us to protect our sensitive data and maintain user privacy.

Just like how your password makes sure your online accounts are only yours.

In this guide, we'll discover a simple and safe process for managing authentication in Next.js applications. We’ll set up client-side authentication that doesn’t require a password using the robust and secure library Auth.js.

It will allow users to log in using their social media accounts, such as Facebook, GitHub, Google, Twitter(X), and so on. Once they've successfully signed up, we'll display their profile picture and email and pull information from their social media accounts.

So, let's dive into a step-by-step guide to adding authentication to your Next.js project using Auth.js (NextAuth.js is becoming Auth.js !).

Prerequisites

Hello, learners! Before we start our authentication journey, let's ensure you're all set:

  1. Curiosity: Check!
  2. Next.js Basics: You're good if you've worked around with Next.js a bit.
  3. React: A basic understanding of React.js
  4. Node.js and npm/yarn: Install Node.js and pick npm or yarn.
  5. Code Editor: Any editor you like.
  6. Command Line: Basic command-line skills.

Feeling confident? Let's start! 🚀

What is Auth.js?

Auth.js is an open-source package built for authentication in the Next.js application. It is being gradually developed to provide authentication solutions in any web framework or library. You can read more about it on the Authjs website.

It is a completely secured and flexible authentication library designed to integrate with any OAuth service( like Google, GitHub, Facebook, and more), with full support for passwordless sign-in.

With Auth.js, you can implement authentication without dealing with complex authentication protocols and API providers. It's a great tool that makes authentication easier and boosts the security of Next.js projects.

Key Features of Auth.js

Easy: Built-in support for popular services like Google and Facebook, provides email/passwordless/magic link authentication, allows usage with various username/password stores, and is compatible with OAuth services.

Flexible: Designed for serverless architecture, adaptability to different environments, compatibility with multiple database options, and offering the choice between database sessions or JWT for authentication.

Secure: Features like utilizing signed, prefixed, server-only cookies, incorporating HTTP POST + CSRF Token validation, and supporting JWT with JWS/JWE/JWK for advanced security.

Setting Up the Next.js Project

To get started, you can either create a new Next.js project or use an existing one. Here's a step-by-step guide to help you get started:

Installation: Create a folder named next-auth-app or any other name you want.

Open your command line and navigate to your Next.js project's directory. Then, run the below command:

npx create-next-app@latest

You will get a series of questions prompted on your terminal. Select the same options as shown in the screenshot below:

Adding Authentication to Next.js Project Using Auth.js: A Step-by-Step Guide

In the project named question, we have put . (dot) as we are already in the project directory.

Now, launch the development server by using the command below:

npm run dev 

By default, the project will run on port 3000. Open your browser and visit to http://localhost:3000. You should see the page displayed as:

Adding Authentication to Next.js Project Using Auth.js: A Step-by-Step Guide

Setting Authentication with Auth.js

Now that we've successfully set up the Next.js starter application, it's time to add authentication for our Next.js project using Auth.js.

This section on configuring authentication with Auth.js will go through the following steps:

  • Installing NextAuth.js
  • Setting up a GitHub OAuth app
  • Creating a Google OAuth app

Let's begin by installing Auth.js. The installation process is straightforward, as it's available as an NPM package.

Installing Auth.js

Open your command line and navigate to your Next.js project's directory. Then, run the command below:

npm i next-auth

Once the installation is complete, you can configure Auth.js for your project.

In our demonstration, we'll allow users to sign in to our application using their GitHub or Google accounts.

Creating a GitHub OAuth app

Our next step involves adding a GitHub Authentication Provider, which allows users to access our application through their GitHub accounts. However, before we proceed, we must create a GitHub OAuth app.

Creating a GitHub OAuth app involves several steps. Here's a step to proceed:

Navigate to Developer Settings

  • Log in to your GitHub account.
  • Click on your profile picture in the top right corner.
  • From the dropdown, select "Settings."
  • On the left sidebar, scroll down and select "Developer settings."

You can also directly visit the GitHub OAuth Apps page. Now you will get a webpage as shown below:

Adding Authentication to Next.js Project Using Auth.js: A Step-by-Step Guide

or

Adding Authentication to Next.js Project Using Auth.js: A Step-by-Step Guide

Now, Click the "Register New Application" if you are first time here or you will get the "New OAuth App" button if you already have another GitHub OAuth app.

OAuth App Configuration

Fill out the following details for your GitHub OAuth app:

  • Application name: Give your app a name.
  • Homepage URL: The URL to your app's homepage. Since we're currently in development mode, we'll need to input the complete URL of our development server. In this case, the URL is http://localhost:3000.
  • Application description: A brief description of your app and its purpose.
  • Authorization callback URL: The URL where GitHub should redirect users after they authorize your app.
Adding Authentication to Next.js Project Using Auth.js: A Step-by-Step Guide

Click the "Register application" button to generate your OAuth app.

After registration, GitHub generates a unique Client ID and Client Secret specifically for our newly created application. Please copy both the Client ID and Client Secret key to your clipboard. If needed, you can click on "Generate new client secret" to obtain a new Client Secret.

Adding Authentication to Next.js Project Using Auth.js: A Step-by-Step Guide

We have successfully created a Github OAuth application and got the Github Client ID and secrets for our further process.

Configuring Environment Variables

You'll need to configure environment variables to set up Auth.js authentication within the Next.js application.

Here's how you can create a .env file in a Next.js project and include the GitHub OAuth app credentials, NextAuth Secrets

Create a new file in your Next.js project's root directory and name it .env.

Add GitHub OAuth Credentials to .env

  • Open the .env file in a text editor.
  • Add your GitHub OAuth app credentials as environment variables like this:

GITHUB_CLIENT_ID=your_client_id GITHUB_CLIENT_SECRET=your_client_secret

Replace your_client_id and your_client_secret with the values you obtained when creating the GitHub OAuth app.

Now, Generate the NEXTAUTH_SECRET variable using the command :

openssl rand -base64 32

It will generate a random key for your Next.js application

Adding Authentication to Next.js Project Using Auth.js: A Step-by-Step Guide

Note: If you don’t provide a NEXTAUTH_SECRET variable, NextAuth.js will automatically generate a new key at the start of every server. That will make all your signed tokens and sessions invalid every time your server restarts. You are strongly recommended to provide your own NEXTAUTH_SECRET variable for consistent sessions.

Our .env contains these lines of code; copy and paste them:

GITHUB_CLIENT_ID=<Github_Client_Id>
GITHUB_CLIENT_SECRET=<Github_Client_Secret>

NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=<NEXTAUTH_SECRET_KEY>

Replace <GITHUB_CLIENT_ID>, <GITHUB_CLIENT_SECRET>, and <NEXTAUTH_SECRET_KEY> with your GitHub client, secret key, and your NextAuth secret.

Remember, keep your .env file safe and never commit it to a public repository since it contains sensitive information like your GitHub OAuth app credentials.

Now, get back to our App and Create an api/auth/[…nextauth]/route.js file in the app directory and add the following code in the route.js file:

import NextAuth from "next-auth/next";
import GithubProvider from "next-auth/providers/github";

const handler = NextAuth({
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
    }),
  ],
});

export { handler as GET, handler as POST };

In the above code snippet, we import the GitHubProvider from "next-auth/providers/github." It creates a handler responsible for handling authentication requests.

The GitHub client ID and secret are fetched from the environment variables GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET. Finally, we export this handler with the GET and POST, signifying that it will handle both HTTP requests for authentication routes.

Then, navigate to http://localhost:3000/api/auth/signin, and you should see this:

Adding Authentication to Next.js Project Using Auth.js: A Step-by-Step Guide

Similarly, we can add Google Outh after generating CLIENT_ID and CLIENT_SECERT_ID and adding it to the .env file. Follow the docs to generate Google OAuth credentials.

The routes file code will look like this:

import NextAuth from "next-auth/next";
import GithubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";


const handler = NextAuth({
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
});

export { handler as GET, handler as POST };

We successfully added authentication to the Next.js project using Auth.js with Github and Google providers.

Conclusion

In this guide, we successfully added user authentication to the Next.js project using the Auth.js library. NextAuth.js is a secured library that allows us to identify our users, obtain user profile information, and render them in our front end.

Implementing authentication can be difficult, but Auth.js has made it easy.

This tutorial will guide you in implementing NextAuth authentication in the Next.js application.

We covered most of the use cases and implemented authentication using OAuth providers like Github and Google, but you can do a lot more with Auth.js. Such as adding a JSON Web Token database, securing pages, and more.

Please check out this documentation to enhance your learning.

Tags:
Share This Post

Related Articles

11+ Best Next.js E-commerce Templates for 2024

Sumaiya Afrin Kanak

11+ Best Next.js E-commerce Templates for 2024

Building a successful e-commerce website is no small feat! Especially when you are coding it from scratch. Designing a u

Read More
11+ Best Next.js Boilerplates and Starter Kit for 2024

Vinish Bhaskar

11+ Best Next.js Boilerplates and Starter Kit for 2024

Don't waste time searching for the perfect Next.js setup. We've curated a list of 11+ Next.js boilerplates to try in 2

Read More
21+ Best Next.js Admin Dashboard Templates - 2024

Vinish Bhaskar

21+ Best Next.js Admin Dashboard Templates - 2024

Are you looking for an Admin Dashboard Template for your Next.js project? Look no further! We've curated a list of 21+

Read More