Implementing Authentication with Next.js and NextAuth.js
Jul 30, 2025 am 04:29 AMInstall next-auth and create API routing files app/api/auth/[...nextauth]/route.js Configure Google login and secret; 2. Set GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, and NEXTAUTH_SECRET in .env.local; 3. Use the signIn and signOut methods to add login and logout buttons and wrap the application with SessionProvider; 4. Protect individual pages through getServerSession or use the withAuth middleware to protect specified routes; 5. Optionally extend session data, add user roles or IDs through callbacks; 6. Optionally use Credentials The provider supports email password login and requires back-end verification; 7. It is recommended to combine Prisma and @auth/prisma-adapter to persist user and session data to achieve a complete authentication system.
Implementing authentication in a Next.js app doesn't have to be complicated — NextAuth.js (now part of Auth.js ) makes it easy to add secure login, user sessions, and social or email/password sign-ins with minimal setup. Here's how to get it working quickly and correctly.

Setting Up NextAuth.js in a Next.js App
Start by installing the required packages:
npm install next-auth
Next.js App Router (v13) uses route handlers. Create an API route for NextAuth under app/api/auth/[...nextauth]/route.js
:

import NextAuth from 'next-auth'; import GoogleProvider from 'next-auth/providers/google'; const handler = NextAuth({ Providers: [ GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }), ], secret: process.env.NEXTAUTH_SECRET, }); export { handler as GET, handler as POST };
? Make sure to set up your
.env.local
file with the required environment variables:GOOGLE_CLIENT_ID=your-google-client-id GOOGLE_CLIENT_SECRET=your-google-client-secret NEXTAUTH_SECRET=your-secure-secret-hereThe
NEXTAUTH_SECRET
is critical — use a strong random string (generate one withopenssl rand -base64 32
).
Adding Sign In / Sign Out Buttons
Use the signIn()
and signOut()
methods from next-auth/react
in your components:
'use client'; import { signIn, signOut, useSession } from 'next-auth/react'; export default function AuthButton() { const { data: session } = useSession(); if (session) { Return ( <div> <p>Welcome, {session.user?.email}</p> <button onClick={() => signOut()}>Sign Out</button> </div> ); } Return ( <button onClick={() => signIn('google')}> Sign In with Google </button> ); }
? Wrap your app with the
SessionProvider
inlayout.js
orRootLayout
:import { SessionProvider } from 'next-auth/react'; export default function RootLayout({ children }) { Return ( <html lang="en"> <body> <SessionProvider>{children}</SessionProvider> </body> </html> ); }
Protecting Routes and Middleware
To protect certain pages from unauthenticated users, check session status in a Server Component or via middleware.
Option 1: Protect a Page Using Server Component
import { getServerSession } from 'next-auth'; import { redirect } from 'next/navigation'; export default async function Dashboard() { const session = await getServerSession(); if (!session) { redirect('/api/auth/signin'); } return <div>Protected Dashboard</div>; }
Option 2: Use Middleware (Recommended for Global Protection)
Create middleware.js
in the root or app
directory:
import { withAuth } from 'next-auth/middleware'; export default withAuth({ pages: { signIn: '/login', }, }); // Apply middleware only to specific routes export const config = { matcher: ['/dashboard', '/profile/:path*'], };
This protects /dashboard
and any /profile/...
routes unless the user is signed in.
Extending Session Data (Optional)
By default, the session only includes basic user info. To add more (like role or ID), use callbacks:
const handler = NextAuth({ Providers: [...], callbacks: { async session({ session, token }) { session.user.id = token.sub; session.user.role = token.role || 'user'; return session; }, async jwt({ token, user }) { if (user) { token.role = user.role; // assuming you store role in your DB } return token; }, }, });
Now session.user.id
and session.user.role
are available client-side.
Supporting Email/Password Login
Enable credentials using the Credentials provider (note: not recommended alone without backend validation):
import CredentialsProvider from 'next-auth/providers/credentials'; CredentialsProvider({ name: 'Credentials', credentials: { email: { label: 'Email', type: 'email' }, password: { label: 'Password', type: 'password' }, }, async authorize(credentials) { // Add logic to verify credentials against your database const user = await verifyUser(credentials.email, credentials.password); return user ? { id: '1', name: user.name, email: user.email } : null; }, }),
?? This method doesn't create real sessions by itself — always validate securely and consider combining with a database adapter.
Using a Database (Optional but Recommended)
To persist users, link a database using Prisma and an adapter:
npm install prisma @prisma/client @auth/prisma-adapter
Update your NextAuth
config:
import { PrismaAdapter } from '@auth/prisma-adapter'; import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); const handler = NextAuth({ adapter: PrismaAdapter(prisma), Providers: [...], });
This enables user creation, session storage, and account linking.
Basically, that's it. With just a few files and solid environment setup, you've got secure, scalable auth in your Next.js app — supporting social logins, protected routes, and even database persistence. Not magic, just well-designed tools working together.
The above is the detailed content of Implementing Authentication with Next.js and NextAuth.js. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In iOS 17, Apple introduced several new privacy and security features to its mobile operating system, one of which is the ability to require two-step authentication for private browsing tabs in Safari. Here's how it works and how to turn it off. On an iPhone or iPad running iOS 17 or iPadOS 17, if you have any Private Browsing tab open in Safari and then exit the session or app, Apple's browser now requires Face ID/TouchID authentication or a passcode to access again they. In other words, if someone gets their hands on your iPhone or iPad while it's unlocked, they still won't be able to view it without knowing your passcode

Single sign-on (SSO) is an authentication mechanism that allows users to authenticate across multiple applications and sites using a single set of credentials, such as a username and password. This mechanism can improve user experience and efficiency while also enhancing security. In PHP, implementing single sign-on requires some specific methods. Below we will introduce how to implement single sign-on in PHP. We will divide it into the following steps: Create a user authentication center (AuthenticationCenter) using OAuth2

Implementing user authentication using middleware in the Slim framework With the development of web applications, user authentication has become a crucial feature. In order to protect users' personal information and sensitive data, we need a reliable method to verify the user's identity. In this article, we will introduce how to implement user authentication using the Slim framework’s middleware. The Slim framework is a lightweight PHP framework that provides a simple and fast way to build web applications. One of the powerful features is the middle

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

With the rapid development of the Internet and mobile Internet, more and more applications require authentication and permission control, and JWT (JSON Web Token), as a lightweight authentication and authorization mechanism, is widely used in WEB applications. Beego is an MVC framework based on the Go language, which has the advantages of efficiency, simplicity, and scalability. This article will introduce how to use JWT to implement authentication in Beego. 1. Introduction to JWT JSONWebToken (JWT) is a

How to use permission control and authentication in C# requires specific code examples. In today's Internet era, information security issues have received increasing attention. In order to protect the security of systems and data, permission control and authentication have become an indispensable part for developers. As a commonly used programming language, C# provides a wealth of functions and class libraries to help us implement permission control and authentication. Permission control refers to restricting a user's access to specific resources based on the user's identity, role, permissions, etc. A common way to implement permission control is to

Best Practices for Using OAuth2 for Authentication in Go Language Using OAuth2 for user authentication is very common in modern web applications. This is a standard protocol that facilitates authorized access to protected resources by third-party applications. The Go language has powerful libraries that support OAuth2, allowing developers to easily implement the OAuth2 process. However, using the OAuth2 protocol correctly is not easy. This article aims to provide information on using OAuth2 for identity in Go language

LDAP (LightweightDirectoryAccessProtocol) is a protocol for accessing distributed directory services. It can be used for tasks such as user authentication, authorization, account maintenance, and data storage. In PHP applications, LDAP can be used as a powerful authentication mechanism to provide powerful authentication and authorization functions for applications. This article will introduce how to use LDAP for user authentication in PHP. The specific content includes: Installation and configuration L
