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 !).
Hello, learners! Before we start our authentication journey, let's ensure you're all set:
Feeling confident? Let's start! 🚀
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.
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.
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:
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:
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:
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.
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
You can also directly visit the GitHub OAuth Apps page. Now you will get a webpage as shown below:
or
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:
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.
We have successfully created a Github OAuth application and got the Github Client ID and secrets for our further process.
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
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
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:
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.
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.
Sumaiya Afrin Kanak
Building a successful e-commerce website is no small feat! Especially when you are coding it from scratch. Designing a u
Read MoreVinish Bhaskar
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 MoreVinish Bhaskar
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