Back to all articles
Next.jsAuthenticationSecurityNextAuth

A Practical Guide to Authentication in Next.js with NextAuth.js

Secure your Next.js application with ease using NextAuth.js (Auth.js). This guide covers setup, social logins, session management, and protecting routes.

A Practical Guide to Authentication in Next.js with NextAuth.js

Authentication is a critical feature for most web applications. NextAuth.js (now part of the Auth.js project) is a complete open-source authentication solution for Next.js applications. It's designed to be easy to use and supports a wide range of providers.

A digital lock with circuitry in the background

Step 1: Installation and Setup

First, add the necessary packages to your project: npm install next-auth

Next, create a dynamic route handler at app/api/auth/[...nextauth]/route.ts. This file will contain all your NextAuth.js configuration.

// app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import GithubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";

export const authOptions = {
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };