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

Vinish Bhaskar

Published on:Oct 16 2023

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 by using a robust and secure library Auth.js.

It will allow users to log in using their social media accounts like Facebook, GitHub, Google, Twitter(X) and so on. Once they've successfully signed up, we'll display their profile picture and email, information we'll pull 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: If you've worked around with Next.js a bit, you're good.
  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 that is built for authentication in the Next.js application. It is being gradually developed to provide authentication solutions in any framework or library on the web. You can read more about it in detail 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 get into the process of adding 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. Since it's available as an npm package, the installation process is straightforward.

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're ready to dive in and configure Auth.js for your project.

In our demonstration, we'll provide users with the option to sign in to our application either using their GitHub or Google accounts.

Creating a GitHub OAuth app

Next, our next step involves adding a GitHub Authentication Provider, allowing 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."

Or You can 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

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

Configuring Environment Variables

In order to proceed with setting up Auth.js authentication within the Next.js application, you'll need to configure environment variables.

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

In your Next.js project's root directory, create a new file 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 actual values you obtained when you created 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: In case, you don’t provide a NEXTAUTH_SECRET variable, NextAuth.js will automatically generate a new key on every server start. That will make all your signed tokens and sessions invalid every time your server restarts. It is 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 types of 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 have successfully, added authentication to the Next.js project using Auth.js with Github provider and Google provider.

Conclusion

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

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

This tutorial was aimed to guide how to implement authentication using NextAuth in the Next.js application.

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

Please check out this documentation to enhance your learning.

Tags:
Share This Post

Related Articles

21+ Best Next.js Admin Dashboard Templates - 2024

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
21+ Best Headless CMS for Next.js in 2024

21+ Best Headless CMS for Next.js in 2024

Are you looking for a headless CMS for Next.js website? But confused about which one to choose. We know the struggle of

Read More
Next.js vs Nuxt: Which one is Better in 2024?

Next.js vs Nuxt: Which one is Better in 2024?

Hey developers 👋, thanks for stopping by! Imagine you're in a cool superhero movie, and you get to pick your coding her

Read More